I am using AngularJS and I have a requirement in which I need to repeat an element after a particular index. So, let's say my code is:
<label ng-repeat="stones in rocks">
<a href="#">Rock {{$index}}</a>
<i class="icon-trash"></i>
</label>
Now what I wish is that <i class="icon-trash"></i>
be repeated only after index 3. That is from the fourth stone onwards, I wish to see the recycle bin. How do I achieve this?
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index . Save this answer.
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.
AngularJS ng-repeat Directive The 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.
The controller creates a child scope and the ng-repeat , which will create an LI element for each item in the list of To Do items. It also creates a new scope for each element.
ng-show can take an expression:
<label ng-repeat="stones in rocks">
<a href="#">Rock {{$index}}</a>
<i class="icon-trash" ng-show="$index > 2"></i><!--$index is 0-based-->
</label>
As of version 1.1.5, you can keep the unwanted elements out of the DOM with
<i class="icon-trash" ng-if="$index > 2"></i>
You might simply hide it in first 3 iterations, using ng-show:
<label ng-repeat="stones in rocks">
<a href="#">Rock {{$index}}</a>
<i class="icon-trash" ng-show="$index>2"></i>
</label>
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