Get the index (counter) of an 'ng-repeat' item with AngularJS?

67,153

Solution 1

Angularjs documentation is full of examples, you just need to take some time and explore it.

See this example here : ngRepeat example , it's the same case.

<ul>
    <li ng-repeat="question in questions | filter: {questionTypesId: questionType, selected: true}">
        <div>
            <span class="name">
                {{$index + 1}} {{ question.questionText }}
            </span>
        </div>
        <ul>
            <li ng-repeat="answer in question.answers">
                <span class="name">
                    {{answer.selector}}. {{ answer.answerText }}
                </span>
            </li>
        </ul>
    </li>
</ul>

Solution 2

Reached here by searching for something similar.

Here is what worked for me.

{{$index + 1}}

+1 is added because the index starts from 0.

Solution 3

There are two ways to get an index for the given array in ng-repeat

Using $index

<th ng-repeat="n in [].constructor(3 + 1) track by $index">{{$index}}</th>

Using a counter

This method is useful when you have nested ng-repeat and you need counters for both loops...the following example uses counter row. Although track by $index is required, it is not used for the logic.

<tr ng-repeat="(row, y) in getNumber(h.seats.length, 3) track by $index">
                    <td>{{row+1}}</td>

In both cases counter starts with 0 and you can offset using +1 if you like

Share:
67,153
lascoff
Author by

lascoff

Updated on November 21, 2020

Comments

  • lascoff
    lascoff over 3 years

    I am using AngularJS and its ng-repeat directive to display a sequence of questions. I need to number each question starting with 1. How do I display and increment such a counter with ng-repeat? Here is what I have so far:

    <ul>
        <li ng-repeat="question in questions | filter: {questionTypesId: questionType, selected: true}">
            <div>
                <span class="name">
                    {{ question.questionText }}
                </span>
            </div>
            <ul>
                <li ng-repeat="answer in question.answers">
                    <span class="name">
                        {{answer.selector}}. {{ answer.answerText }}
                    </span>
                </li>
            </ul>
        </li>
    </ul>