我用一个简单的方法ng-repeat来生成国家列表。每个列表中都有一个可以扩展和折叠的隐藏行/ div。
ng-repeat
我面临的问题是,在将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?
您可以使用$index https://docs.angularjs.org/api/ng/directive/ngRepeat
$index
<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>