如何避免重复id与ng-repeat + bootstrap崩溃

时间:2015-12-14 02:35:13

标签: javascript css angularjs twitter-bootstrap

我构建了嵌套的Bootstrap .collapseng-repeat。它们有3个级别:distsadminsagents

为了使Bootstrap崩溃工作,您需要为每个.collapse使用不同的ID。所以我在id中添加了$index + 1

  <div id="dists" class="list-container">
    <div class="dist" ng-repeat="dist in dists track by $index">
      <a href="javascript:;" data-toggle="collapse" data-target="#admins-{{$index + 1}}" ng-click="updatePanels()">
      </a>
      <div id="admins-{{$index + 1}}" class="list-container collapse">
        <div class="admin" ng-repeat="admin in dist.admins track by $index">
          <a href="javascript:;" data-toggle="collapse" data-target="#agents-{{$index + 1}}" ng-click="updatePanels()">
          </a>
          <div id="agents-{{$index + 1}}" class="list-container collapse">
            <div class="agent" ng-repeat="agent in admin.agents track by $index">
          </div>
        </div>
      </div>
    </div>
  </div>

它有效 - 除了我最终有重复的ID:

.dist
  #admin-1 <- repeated
    #agent-1
    #agent-2

.dist
  #admin-1 <- repeated

避免这种情况的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

对于内部循环,您可以通过$index访问外部$parent.$index。例如

<div id="admins-{{$parent.$index + 1}}-{{$index + 1}}"

和第3级(代理),使用$parent.$parent.$index访问 dist 索引。

请参阅https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$parent

另一个选项和可能更简洁的选项是通过ng-init将索引分配给本地范围的属性。例如

<div class="dist" ng-repeat="dist in dists track by $index"
    ng-init="distIndex = $index + 1">
    <div id="admins-{{distIndex}}">
        <div class="admin" ng-repeat="admin in dist.admins track by $index"
            ng-init="adminIndex = $index + 1">
            <!-- and so on -->