Angularjs - How to apply different class in <tr> conditionally to repeat directive Angularjs - How to apply different class in <tr> conditionally to repeat directive angularjs angularjs

Angularjs - How to apply different class in <tr> conditionally to repeat directive


Normally you would use ngClassOdd (http://docs.angularjs.org/api/ng.directive:ngClassOdd) and ngClassEven (http://docs.angularjs.org/api/ng.directive:ngClassEven) directives like this:

<tr ng-repeat="item in items" ng-class-odd="'class1'" ng-class-even="'class2'">

Here is the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/hNHJ4/1/

Unfortunately there is an issue where the mentioned directives are not working correctly when rows are removed: https://github.com/angular/angular.js/issues/1076

As a work around you can use the ngClass directive (http://docs.angularjs.org/api/ng.directive:ngClass) with the $index variable exposed by a repeater:

<tr ng-repeat="item in items" ng-class="{class1 : $index%2==0, class2 : !($index%2==0)}">

Here is the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/am7xs/

It is not super-clean, but could be improved (for example, by exposing a function in a root scope, something like:

ng-class="getClass($index,'class1','class2')"

till the mentioned bug is fixed


If this is just for styling you can just use CSS

tr:nth-child(odd) { ... }tr:nth-child(even) {...}

see http://jsfiddle.net/5MSDC/ for an example