Can I filter ng-repeat with the $odd or $even properties?

Viewed 27208

I am trying to auto filter an ng-repeat list by even index. Is it possible to do this somehow? Here's what I am trying but it isn't working:

<div data-ng-repeat="thing in things | filter:$even" >
     <div>{{thing.name}}</div>
</div>

Is there a proper way of achieving this?

4 Answers

The documentation of ng-repeat tells us about the special properties we can use in such case. You can use:

  • $even -> true if the iterator position $index is even (otherwise false).
  • $odd -> true if the iterator position $index is odd (otherwise false).

Code examples:

<div data-ng-repeat="thing in things" ng-if="$even">
     <div>{{thing.name}}</div>
</div>

or

<div data-ng-repeat="thing in things" ng-if="$odd">
     <div>{{thing.name}}</div>
</div>

or

<div data-ng-repeat="thing in things" ng-class="{'my-odd-class': $odd}">
     <div>{{thing.name}}</div>
</div>

or

<div data-ng-repeat="thing in things" ng-class="{'my-even-class': $even}">
     <div>{{thing.name}}</div>
</div>
Related