AngularJS ngRepeat: how to differentiate even/odd elements?

All we need is an easy explanation of the problem, so here it is.

I’m new to angular and trying to do the following:

<tr data-ng-repeat="element in awesomeThings">
<div ng-if="$index %2 == 0">
    <td class="even">
        <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">
            {{element}}
        </a>
    </td>
</div>
<div ng-if="$index %2 != 0">
    <td class="odd">
        <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">
            {{element}}
        </a>
    </td>
</div>
</tr>

for the above code, both ng-if is passing. Where I’m making mistake?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Try $even and $odd properties. Refer the documentation.

Like :

<tr data-ng-repeat="element in awesomeThings">
<div ng-if="$even">
    <td class="even">
        <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">
            {{element}}
        </a>
    </td>
</div>
<div ng-if="$odd">
    <td class="odd">
        <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">
            {{element}}
        </a>
    </td>
</div>
</tr>

Method 2

You don’t need to use ng-if to check whether it’s an even or odd element, that functionality is built-in already:

    <tr ng-repeat="element in awesomeThings">
        <span ng-class="$even ? 'odd' : 'even'">{{element}}</span>
   </tr>

Another built-in feature is ng-class which gives you several options to conditionally set a css class, here I’m using the ternary version but there are other ways to use it also.

Here is a working example

Also, here is a good article explaining more about ng-class

Method 3

You can also use ng-class-even and ng-class-odd.

https://docs.angularjs.org/api/ng/directive/ngClassEven
https://docs.angularjs.org/api/ng/directive/ngClassOdd

Method 4

Try this in css:

tr:nth-child(even) {
    background: #CCC
}

tr:nth-child(odd) {
    background: #FFF
}

You could define style for the first item:

tr:first-child {
    background: #84ace6
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply