【问题标题】:how to get the unique number inside ng-repeat?如何在 ng-repeat 中获取唯一编号?
【发布时间】:2013-12-10 17:28:53
【问题描述】:

我正在使用 Angular ng-repeat 来显示引导选项卡。我有一个嵌套的标签。我需要标签元素及其内容的唯一 ID。目前我正在使用 $index 来获取唯一性。但它在父选项卡内的更多棕褐色两个选项卡失败。

var items = ['hello1', 'hello2', 'hello3'];

<ul>
  <li id="yui{{$index+1}}" ng-repeat="item in items"></li>
</ul>

我想要不使用 $index 的项目的唯一 ID。还有其他方法吗?

 <ul>
      <li id="yui1">hello1</li>
      <li id="yui2">hello2</li>
      <li id="yui3">hello3</li>
    </ul>

【问题讨论】:

  • $index在 ngRepeat 中始终是唯一的。向我们展示您的完整代码。

标签: javascript angularjs twitter-bootstrap


【解决方案1】:

您也可以访问父母的唯一索引,所以在您的情况下,它会像

<li id="{{ $parent.$index }}_{{ $index + 1 }} ....

【讨论】:

    【解决方案2】:

    要设置唯一 id 或获取唯一字符串,您可以创建可重用的 angularJS 过滤器,它接受可选参数,如前缀/$index/后缀,然后返回唯一字符串。例如 -

     angular.module('myApp',[ngRoute]).filter('unique',function(){
    
        return function(input,prefix){
        var uniqueID = '';
        // generate unique string.
        return uniqueID;
        }
    });
    

    然后从你的视野中 -

    <li id="{{$index | unique:'tab_'}}">test1</li>
    

    【讨论】:

    • 这将导致无限的 $digest 循环。
    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    相关资源
    最近更新 更多