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

假如想象 提交于 2020-01-11 18:18:17

问题


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>

回答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>



回答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.




回答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



来源:https://stackoverflow.com/questions/22335095/get-the-index-counter-of-an-ng-repeat-item-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!