AngularJS – ng重复分配/生成新的唯一ID

前端之家收集整理的这篇文章主要介绍了AngularJS – ng重复分配/生成新的唯一ID前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用简单的ng重复来生成国家列表。每个列表中都有一个隐藏的行/ 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重复中分配动态/增量ID?

您可以使用$ 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>
原文链接:/angularjs/144594.html

猜你在找的Angularjs相关文章