angularjsangularjs-ng-class

ng-class expression only evaluates scope property once


I have 2 divs with an ng-class applied to evaluate a $scope property, called {{stepNumber}}.

 <div id="step0" class="col-xs-2" ng-class="{{stepNumber}} == 0 ? 'active' : {{stepNumber}} > 1 ? 'complete' : 'disabled' ">

 <div id="step1" class="col-xs-2" ng-class="{{stepNumber}} == 1 ? 'active' : {{stepNumber}} > 1 ? 'complete' : 'disabled' ">

The first time the page is loaded, {{stepNumber}} is 0,

1st div gets class active, 2nd div gets class disabled.

When I click a button that uses ng-click to increment the property value by doing $scope.stepNumber++;, the divs do not reevaluate the ng-class expression.

{{stepNumber}} is now 1 but the 1st div class is still active, 2nd div class is still disabled

How can I get the ng-class to reevaluate the expression?


Solution

  • That's not how ng-class works. Read its documentation carefully. The correct code would be:

    ng-class="{active: stepNumber == 0, complete: stepNumber > 1, disabled: stepNumber != 0 && stepNumber <= 1}"
    

    or

    class="col-xs-2, {{stepNumber == 0 ? 'active' : stepNumber > 1 ? 'complete' : 'disabled' }}"
    

    or

    ng-class="stepNumber == 0 ? 'active' : stepNumber > 1 ? 'complete' : 'disabled'"