AngularDoubts AngularDoubts - 28 days ago 6
AngularJS Question

Alternative row coloring in html table with ng-repeat

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>




Answer

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.