klferreira
klferreira

Reputation: 332

How can i make Bootstrap collapse work properly with nested AngularJS ng-repeat?

When i click any of the collapse toggle icons, it only works for the first li generated by the ng-repeat, how can i fix this so it only collapses it's parent 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>

Upvotes: 1

Views: 895

Answers (1)

Matthew Cawley
Matthew Cawley

Reputation: 2818

Use $index to ensure you're targeting unique ids. So make the following 2 changes to your code:

  • On the inner <ul> tag, id="collapse{{ $index }}"
  • On the first <i> tag, 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

Upvotes: 1

Related Questions