一尘不染

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

angularjs

我用一个简单的方法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>

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


阅读 282

收藏
2020-07-04

共1个答案

一尘不染

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