AngularJS - ng-repeat 来分配/生成一个新的唯一 ID [英] AngularJS - ng-repeat to assign/generate a new unique ID

查看:28
本文介绍了AngularJS - ng-repeat 来分配/生成一个新的唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • {{country.name}} 的人口为 {{country.population}}<div id="country1"><p>展开/折叠内容
  • <li data-show="#country2">{{country.name}} 的人口为 {{country.population}}<div id="country2"><p>展开/折叠内容

    <li data-show="#country3">{{country.name}} 的人口为 {{country.population}}<div id="country3"><p>展开/折叠内容

    <li data-show="#country4">{{country.name}} 的人口为 {{country.population}}<div id="country4"><p>展开/折叠内容

    使用 ng-repeat 的新代码:

  • {{country.name}} 的人口为 {{country.population}}<div id="???"><p>展开/折叠内容
  • 如何在我的 ng-repeat 中分配动态/增量 ID?

    解决方案

    您可以使用 $index https://docs.angularjs.org/api/ng/directive/ngRepeat

  • {{country.name}} 的人口为 {{country.population}}<div id="country-{{$index}}"><p>展开/折叠内容
  • Im using a simple ng-repeat to generate a list of countries. Within each list is a hidden row/div that can be expanded and collapsed.

    The issue that i am facing, is that before i introduced Angular into my application, i manually hard-coded the element's ID, for example:

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

    New code using 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>
    

    How can i assign a dynamic/incremental id in my ng-repeat?

    解决方案

    You can use $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 - ng-repeat 来分配/生成一个新的唯一 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    其他开发最新文章
    热门教程
    热门工具
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆