Search code examples
javascriptangularjsnestedangularjs-ng-repeat

Angular JS ng-class-odd in nested ng-repeats


I'm trying to develop a very generic table outputter - no set number of rows or columns. As such, I've got nested ng-repeat attributes, as such:

<table>
    <tr ng-repeat="row in rowList">
        <td ng-repeat="col in colList">{{printCell(row,col)}}</td>
    </tr>
</table>

It's working great! Until I try to use ng-class-even and ng-class-odd to change the background color of the rows accordingly.

If I put the ng-class-*** statements on the td tag, I get alternating column colors.

If I put the ng-class-*** statements on the tr tag, I don't get any class assignment - they all stay default.

I want alternating row colors. How do I go about doing this?


Solution

  • The value of ng-class-odd and ng-class-even can be a string: ng-class-odd="'myClass'" or an expression ng-class-odd="{myClass: boolExpression}"

    Also:

    Angular 1.2+: ng-class="{even: $even, odd: $odd}"

    <table>
        <tr ng-repeat="row in rowList" ng-class="{even: $even, odd: $odd}">
            <td ng-repeat="col in colList">{{printCell(row,col)}}</td>
        </tr>
    </table>
    <hr />
    

    Angular < 1.2 ng-class="{even: !($index%2), odd: ($index%2)}"

    <table>
        <tr ng-repeat="row in rowList" ng-class="{even: !($index%2), odd: ($index%2)}">
            <td ng-repeat="col in colList">{{printCell(row,col)}}</td>
        </tr>
    </table>
    

    Examples: http://jsfiddle.net/TheSharpieOne/JYn7S/1/