Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ngRepeat: how to differentiate even/odd elements?

Tags:

angularjs

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="#">
            {{element}}
        </a>
    </td>
</div>
<div ng-if="$index %2 != 0">
    <td class="odd">
        <a href="#">
            {{element}}
        </a>
    </td>
</div>
</tr>

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

like image 413
batman Avatar asked Oct 09 '14 06:10

batman


4 Answers

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

like image 200
Lakatos Gyula Avatar answered Oct 25 '22 15:10

Lakatos Gyula


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="#">
            {{element}}
        </a>
    </td>
</div>
<div ng-if="$odd">
    <td class="odd">
        <a href="#">
            {{element}}
        </a>
    </td>
</div>
</tr>
like image 33
kvothe Avatar answered Oct 25 '22 15:10

kvothe


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

like image 29
aarosil Avatar answered Oct 25 '22 15:10

aarosil


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
}
like image 33
Oleksandr Bondarchuk Avatar answered Oct 25 '22 14:10

Oleksandr Bondarchuk