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.
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.
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.
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.
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With