AngularJS - ng-repeat to assign/generate a new uni

2019-01-22 12:40发布

Im using a simple ng-repeat to generate a list of countries. Within each list is a hidden row/div that can be expanded and collapsed.

The issue that i am facing, is that before i introduced Angular into my application, i manually hard-coded the element's ID, for example:

<li data-show="#country1">
    {{country.name}} has population of {{country.population}}

    <div id="country1">
         <p>Expand/collapse content
    </div>
</li>
<li data-show="#country2">
    {{country.name}} has population of {{country.population}}

    <div id="country2">
         <p>Expand/collapse content
    </div>
</li>
<li data-show="#country3">
    {{country.name}} has population of {{country.population}}

    <div id="country3">
         <p>Expand/collapse content
    </div>
</li>
<li data-show="#country4">
    {{country.name}} has population of {{country.population}}

    <div id="country4">
         <p>Expand/collapse content
    </div>
</li>

New code using ng-repeat:

<li ng-repeat="country in countries" data-show="????">
    {{country.name}} has population of {{country.population}}

    <div id="???">
         <p>Expand/collapse content
    </div>
</li>

How can i assign a dynamic/incremental id in my ng-repeat?

2条回答
劫难
2楼-- · 2019-01-22 13:15

{{$index+1}} will show 1-5 for every page of pagination in order to change serial no as per page no of pagination, use {{$index+curPage*5+1}}, where curPage is your current page in pagination.

查看更多
Viruses.
3楼-- · 2019-01-22 13:18

You can use $index https://docs.angularjs.org/api/ng/directive/ngRepeat

<li ng-repeat="country in countries" data-show="????">
    {{country.name}} has population of {{country.population}}

    <div id="country-{{$index}}">
        <p>Expand/collapse content
    </div>
</li>
查看更多
登录 后发表回答