AngularJS - ng-repeat分配/生成新的唯一ID

时间:2014-04-24 09:21:13

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat ng-repeat

我使用简单的ng-repeat来生成国家/地区列表。每个列表中都有一个隐藏的行/ div,可以展开和折叠。

我面临的问题是,在我将Angular引入我的应用程序之前,我手动硬编码了元素的ID,例如:

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

使用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>

如何在ng-repeat中分配动态/增量ID?

3 个答案:

答案 0 :(得分:39)

您可以使用$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>

答案 1 :(得分:0)

{{$index+1}}将为每个分页页面显示1-5,以便按照每页分页更改序列号,使用{{$index+curPage*5+1}},其中curPage是您分页的当前页面。

答案 2 :(得分:0)

当您嵌套ng-repeat时,可​​能需要以下类似的内容:

<label id="country-{{$parent.$index}}-{{$index}}" ng-repeat="city in country.cites"> {{city.name}} </label>