比较 AngularJS 指令中的两个整数

Comparing two integers in AngularJS directive

我想根据关联用户的 graduation_yearng-showng-if 指令有条件地显示或隐藏元素。

如果 graduation_year 大于或等于当前年份(即用户是 "active"),则应显示该元素,如果小于当前年份,则应隐藏该元素。

在我试过的视图中

<div data-ng-repeat="user in data.group.users">    
  <div ng-show="{{ user.graduation_year }} >= {{ date | date:'yyyy' }}">Active</div>
</div>

并在控制器中

$scope.date = new Date();

但无论如何它都将其视为错误,即使输出显示“2017 >= 2015”和“2014 >= 2015”(只是几个例子),所以我应该得到不同的结果。当我尝试 ng-if 时,无论如何它们都被视为 true。

大括号破坏了您的代码。

<div data-ng-repeat="user in data.group.users">    
  <div ng-show="user.graduation_year >= (date | date:'yyyy')">Active</div>
</div>

您错误地使用了变量插值。

在 ng-show 中,您不需要 {{ 和 }}。

此外,您正在组合比较运算和筛选器。 这确实有效,但让代码在视觉上尽可能简单可能对您有益。

试试这个:

<div data-ng-repeat="user in data.group.users">    
  <div ng-show="isActive( user )">Active</div>
</div>

module.controller( 'UserCtrl', [ '$scope', function( $scope ){
    $scope.date = new Date()
    $scope.isActive = function( user ){      
        return user.graduation_year >= $scope.date.getFullYear()
    }
 }])
}