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

27

我正在使用简单的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个回答

42

如何更改语法?非常有趣。 - mediaroot
我移除了非标准的 {[{ 和 }]} Angular 插值开始和结束符号。这与问题无关,只会使它更加复杂,不具有通用性。我在问题和答案中都进行了修改。上面的两条评论是针对此事的,如果现在它们没有意义,那么很抱歉! - Aardvark
谢谢,虽然$index可能不够稳健,但它似乎对于集成测试非常有帮助 - 这就是为什么我查找了这个选项。 - user3864935
嗨@Iridann,$index有时可能不够健壮,例如在读取数组时修改它(https://dev59.com/Smkw5IYBdhLWcg3wdKQv)。您还有哪些情况考虑到了吗? - Eduard Gamonal
有人可以看一下这个吗?https://dev59.com/AFwX5IYBdhLWcg3w8TXM - dark_shadow
显示剩余2条评论

1
当你需要嵌套使用ng-repeat时,可能会需要以下类似的代码:

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接