How to use ng-repeat with filter and $index? How to use ng-repeat with filter and $index? angularjs angularjs

How to use ng-repeat with filter and $index?


In your code, filter apply on 'items' array, not on each array item, that's why it does not work as you expect.

Instead, you can use ng-show (or ng-if):

<ul>    <li ng-repeat="item in items" ng-show="$index % 3 == 0">{{item}}</li></ul>

See: http://jsfiddle.net/H7d26

EDIT: Use ng-if directive if you do not want to add invisible dom elements:

<ul>    <li ng-repeat="item in items" ng-if="$index % 3 == 0">{{item}}</li></ul>


Create a custom filter, for example:

filter('modulo', function(){  return function (arr, div, val) {      return arr.filter(function(item, index){          return index % div === (val || 0);      })  };});

Then change the ng-repeat to:

<ul ng-repeat="item in items | modulo:3">

Or filter by (index % 3 === 1) like:

<ul ng-repeat="item in items | modulo:3:1"> 

http://jsfiddle.net/Tc34P/2/


What you need to do is find the index of "item" in $scope.items. See below

ng-repeat"item in items | filter:(items.indexOf(item)%3 == 0)

So a real world example (for others who come across this solution) would be.

<div ng-repeat="item in filtered = (items | filter:customfilter | orderBy:customsort)">    <div> This is number {{items.indexOf(item)}} in the items list on the scope.</div></div>

The above example will get the correct position regardless of the sorting or filtering