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

Oam*_*Psy 25 angularjs angularjs-directive ng-repeat angularjs-scope angularjs-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>
Run Code Online (Sandbox Code Playgroud)

新代码使用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>
Run Code Online (Sandbox Code Playgroud)

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

Edu*_*nal 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>
Run Code Online (Sandbox Code Playgroud)