Sherin
Sherin

Reputation: 185

what is the use of $index in angularjs?

What is the exact use of $index in angularjs.I have little confusion with using $index in angularjs

<div class="row review" ng-show="mode=='review'">
    <div class="col-sm-4" ng-repeat="question in questions">
        <div ng-click="goTo($index + 1)" class="{{ isAnswered($index) == 'Answered'? 'answered': 'not-answered' }}">{{$index + 1}}. {{ isAnswered($index) }}</div>
    </div>
</div>

Upvotes: 5

Views: 12761

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

They are the keys of array you use in ng-repeat.

You can see the full detail on the doc.

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

You may see the example on docs.

The following result is generated by using $index:

[1] John who is 25 years old.
[2] Jessie who is 30 years old.
[3] Johanna who is 28 years old.
[4] Joy who is 15 years old.
[5] Mary who is 28 years old.
[6] Peter who is 95 years old.
[7] Sebastian who is 50 years old.
[8] Erika who is 27 years old.
[9] Patrick who is 40 years old. 

Here's a part of angularjs code for demo:

<li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
      [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>

Upvotes: 4

Related Questions