Angularjs - How to apply different class in <tr> conditionally to repeat directive
Solution 1
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
Solution 2
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
Aitiow
Updated on June 04, 2022Comments
-
Aitiow almost 2 years
I need to apply a different class to a
<tr>
according to the$index
of the repeat directive. For example<table> <tr ng-repeat="model in list" class="xxx"> <td>...</td> <tr> </table>
I need to apply a different style to
<tr>
depending on whether the index is even and odd.How could I solve this?
-
Trip about 11 yearsI wonder if its possible to append a TR that goes outside the grain of the other TR's.. preferably one with a title header. Like every row is a week, and then a TR is a header for that month or that year but doesn't contain 7 TD's.. I'm getting that this is impossible to do with Angular..
-
Idrees almost 9 yearsActually this is the correct way of doing it. Since it's a CSS class thing, CSS is the best way to do it.
-
Idrees almost 9 yearsThe Who, you've got a typo: tr:nth-child(event) {...} .. it should be even not event.
-
Oded Niv over 8 yearsI would put the "bug is fixed" line before explaining how to work around, emphasized.