Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Repeat after a particular index

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?

like image 809
callmekatootie Avatar asked Mar 11 '13 14:03

callmekatootie


People also ask

How do you pass an index in NG-repeat?

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.

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.

What is Ng-repeat in AngularJS?

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.

Does ng-repeat create a new scope?

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.


2 Answers

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>
like image 106
Eugenio Cuevas Avatar answered Oct 28 '22 13:10

Eugenio Cuevas


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>
like image 31
Stewie Avatar answered Oct 28 '22 12:10

Stewie