Search code examples
angularjsternary-operatorng-class

Angular ng-class ternary doesn't update my template as the model changes


When my page initially loads it properly sets the class using this ng-class ternary operator:

<div ng-class="{{day.current}} ? 'currPeriod' : 'notCurrPeriod'">
    {{day.date | date:"d"}}
</div>

Note - this html is in a template, used by a directive, generated in an ng-repeat

The value of the day {{day.date | date:"d"}} updates, but the class is not applied.

Oddly, my dev tools shows a disparity:

enter image description here

1 = true so it should evaluate to currPeriod but the element class is still notCurrPeriod. I tried $scope.$apply() at the end of the modal change, but that didn't work. How can I get the template to rerun and apply this ternary? or is there a better way to do this?


Solution

  • <div ng-class="{'currPeriod': day.current, 'notCurrPeriod': !day.current}">
      {{day.date | date:"d"}}
    </div>
    

    ng-class doesn't work this way, use the object syntax to acheive what you want, or you can either set a default style when the day isn't in the current period, and apply the class when it is, it would shorten your ng-class statement