How to assign alternate class to rows in Angular JS?
JavascriptAngularjsJavascript Problem Overview
I want to assign alternate class to rows in a table. I am using ng-repeat on
<tr ng-repeat="event in events">
I want to get output like this:
<tr class="odd">...</tr>
<tr class="event">....</tr>
I've tried this (doesn't work):
<tr ng-repeat="event in events" class="$index % 2 == 0? 'event' : 'odd'">
I can't get it to work. Also it seems like Angular is using 'class' attribute to. Why is it doing so? Can I tell AngularJS not to use the class attribute for internal evaluations?
Please help. Thanks!
Javascript Solutions
Solution 1 - Javascript
You should be using the angular directives ngClassEven and ngClassOdd for this.
Have a look at the documentation section for how to use them
http://docs.angularjs.org/api/ng.directive:ngClassEven
http://docs.angularjs.org/api/ng.directive:ngClassOdd
Hope this helps.
Solution 2 - Javascript
From the Angular docs..
Use ng-class-odd ng-class-even
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
Solution 3 - Javascript
As @ganaraj states ng-class-odd and ng-class-even are the right way to do this, but for the benefit of searchers, your initial proposal wasn't far off working in Angular >=1.2.19.
Here is a closely related example of something that would have worked and would also work if coloring more than alternate rows (e.g. every 3 rows):
<div>
<style>
.color0 {
background-color: lightblue;
}
.color1 {
background-color: lightyellow;
}
.color2 {
background-color: lightgray;
}
</style>
<div ng-repeat="result in results" ng-class="'color' + ($index % 3)">
<div>
<p>{{result.myText}}</p>
</div>
</div>
Solution 4 - Javascript
You can also use the ng-class-odd
and ng-class-even
directives directly within the ng-repeat
directive.
<div class="cssOneProductRecord"
ng-repeat='..'
ng-class-odd="'cssProductOdd'"
ng-class-even="'cssProductEven'" >
Which gives us nice alternating classes for each row:
This example is taken from the following page, which also demonstrates how to turn JSON data into a friendly, responsive Master-View page:
Solution 5 - Javascript
Improving Fintan Kearney's answer,
From: https://docs.angularjs.org/api/ng/directive/ngClassOdd
Style.css
.odd {
color: red;
}
.even {
color: blue;
}
index.html
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>