Question

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>
Était-ce utile?

La solution

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>

Autres conseils

Reached here by searching for something similar.

Here is what worked for me.

{{$index + 1}}

+1 is added because the index starts from 0.

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top