Search code examples
javascriptangularjsangularjs-directiveng-showangular-ng-if

Comparing two integers in AngularJS directive


I want to conditionally show or hide an element based on the associated User's graduation_year and the ng-show and ng-if directives aren't working as is.

The element should be shown if the graduation_year is greater than or equal to the current year (i.e. the user is "active"), and hidden if less than the current year.

In the view I've tried

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

and in the controller

$scope.date = new Date();

but it treats it as false no matter what, even though the output is showing "2017 >= 2015" and "2014 >= 2015" (just a couple examples), so I should be getting different outcomes. When I tried ng-if, they were both treated as true no matter what.


Solution

  • You're using the variable interpolation incorrectly.

    Inside ng-show, you don't need {{ and }}.

    Also, you're combining a comparison operation and a filter. This does work, but it may benefit you to keep the code as visually simple as possible.

    Try this:

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

    and

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