如何使用嵌套的AngularJS ng-repeat使Bootstrap崩溃正常工作?

时间:2017-02-10 00:19:20

标签: angularjs twitter-bootstrap

当我点击任何折叠切换图标时,它仅适用于li生成的第一个ng-repeat,我该如何解决这个问题,以便它只折叠它的父li

$scope.data = [{
  label: 'North America',
  children: [{
    label: 'Canada',
    children: ['Toronto', 'Vancouver']
  }, {
    label: 'USA',
    children: ['New York', 'Los Angeles']
  }, {
    label: 'Mexico',
    children: ['Mexico City', 'Guadalajara']
  }]
}, {
  label: 'South America',
  children: [{
    label: 'Venezuela',
    children: ['Caracas', 'Maracaibo']
  }, {
    label: 'Brazil',
    children: ['Sao Paulo', 'Rio de Janeiro']
  }, {
    label: 'Argentina',
    children: ['Buenos Aires', 'Cordoba']
  }]
}];
<ul class="list-group">
  <li class="list-group-item" ng-repeat="item in data">
    <ul class="collapse in" ng-if="item.children" id="collapse">
      <i class="glyphicon glyphicon-minus pull-right" data-toggle="collapse" data-target="#collapse"></i>
      <i class="glyphicon glyphicon-plus pull-right hidden"></i>
      {{item.label}}
      <li class="list-group-item" ng-repeat="sub in item.children">
        {{sub.label}}
      </li>
    </ul>
  </li>
</ul>

1 个答案:

答案 0 :(得分:1)

使用$index确保您定位唯一ID。因此,对您的代码进行以下2项更改:

  • 在内部<ul>代码上,id="collapse{{ $index }}"
  • 在第一个<i>代码data-target="#collapse{{ $index }}"

HTML:

<ul class="list-group">
  <li class="list-group-item" ng-repeat="item in data">
    <ul class="collapse in" ng-if="item.children" id="collapse{{ $index }}">
      <i class="glyphicon glyphicon-minus pull-right" data-toggle="collapse" data-target="#collapse{{ $index }}"></i>
      <i class="glyphicon glyphicon-plus pull-right hidden"></i>
      {{item.label}}
      <li class="list-group-item" ng-repeat="sub in item.children">
        {{sub.label}}
      </li>
    </ul>
  </li>
</ul>

Sample Plunk