Reputation: 499
I have an table which is filled with values using ng-repeat. I need to color the rows of table alternatively with green and yellow color. I tried it out the following way without ng-repeat and it works.
.table-striped>tbody>tr:nth-of-type(odd)
{
background: yellow !important;
}
.table-striped>tbody>tr:nth-of-type(even)
{
background: green !important;
}
<html>
<div><table class="table table-striped">
<thead style="border: 1px solid">
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{value.val1}}</td>
</tr>
<tr>
<td>{{value.val2}}</td>
</tr>
<tr>
<td>{{value.val3}}</td>
</tr>
</tbody>
</table>
</div>
<html>
But it is not working while using ng-repeat as follows(all rows are in yellow itself). Please help.Thanks in advance.
.table-striped>tbody>tr:nth-of-type(odd)
{
background: yellow !important;
}
.table-striped>tbody>tr:nth-of-type(even)
{
background: green !important;
}
<html>
<div><table class="table table-striped">
<thead style="border: 1px solid">
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody ng-repeat="value in values">
<tr>
<td>{{value.val1}}</td>
</tr>
</tbody>
</table>
</div>
<html>
Upvotes: 0
Views: 2049
Reputation: 7179
While I think the solution for OP would be moving the ng-repeat
from <tbody>
to <tr>
, because it matches his intended structure without ng-repeat
; it is entirely possible to color alternatively by using css alone when the ng-repeat
is on the <tbody>
layer.
tbody:nth-of-type(odd)>tr {
background-color: pink;
}
tbody:nth-of-type(even)>tr {
background-color: purple;
}
<table>
<tbody>
<tr><td>row1</td></tr>
</tbody>
<tbody>
<tr><td>row2</td></tr>
</tbody>
<tbody>
<tr><td>row3</td></tr>
</tbody>
</table>
Upvotes: 1
Reputation: 1140
I think you should give ng-repeat="value in values" to tr not to tbody. You ng-repeat on body will repeat body element.
Upvotes: 2
Reputation: 3293
You can add a class to your rows dynamically and then give the style you want.
<tr class="myrow">
$(".myrow:odd").addClass("odditem");
$(".myrow:even").addClass("evenitem");
Upvotes: 1
Reputation: 673
You can use the directive ng-class-odd="'classname'".
<html>
<div>
<table class="table table-striped">
<thead style="border: 1px solid">
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody ng-repeat="value in values">
<tr class="row-color" ng-class-odd="'odd'">
<td>{{value.val1}}</td>
</tr>
<tr class="row-color" ng-class-odd="'odd'">
<td>{{value.val2}}</td>
</tr>
<tr class="row-color" ng-class-odd="'odd'">
<td>{{value.val3}}</td>
</tr>
</tbody>
</table>
</div>
<html>
then in your css you could do the following
.row-color {
background: green;
}
.row-color.odd {
background: yellow;
}
This also gets rid of your !important which is usually regarded as bad practice.
Upvotes: 1