Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use ng-repeat in Angular, while I only want to output some elements of the array. An Example:

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

However, this does not work. Please tell me how to do this; only output exact index of elements.

like image 877
Frankjs Avatar asked Dec 31 '13 13:12

Frankjs


People also ask

How do I filter in NG-repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

How do you use NG-repeat in a table?

Definition and UsageThe ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.


2 Answers

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> 
like image 87
Mickael Avatar answered Sep 20 '22 17:09

Mickael


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/

like image 23
CD.. Avatar answered Sep 22 '22 17:09

CD..