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

后端 未结 3 1989
别那么骄傲
别那么骄傲 2021-02-02 06:42

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 a

相关标签:
3条回答
  • 2021-02-02 07:24

    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

    0 讨论(0)
  • 2021-02-02 07:30

    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>

    0 讨论(0)
  • 2021-02-02 07:42

    Reached here by searching for something similar.

    Here is what worked for me.

    {{$index + 1}}
    

    +1 is added because the index starts from 0.

    0 讨论(0)
提交回复
热议问题