Seth
Seth

Reputation: 334

AngularJS Accordion Expand All Collapse All

I am trying to get the accordions to toggle correctly through the directive ng-click. If I have Item one open how do I get it to expand all the accordions? Item two and Item three will continue to expand and collapse but Item one stays stagnant.

Plunker

Upvotes: 4

Views: 9749

Answers (2)

Brad Zacher
Brad Zacher

Reputation: 3263

alternately you can adjust your buttons so that they just loop through the children.

html:

<div ng-controller="AccordionDemo">
  <div >
      <div class="stuff_in_the_middle" >
          <div ng-repeat="m in results" ng-click="m.open = !m.open" style="margin-bottom:20px">
            <div heading="{{m.label}}" is-open="m.open" style="background-color:#d2d2d2; cursor:pointer" > 
            {{m.label}}
            </div>
            <div ng-show="m.open" style="padding:10px">
              contents
            </div>
          </div>
          <span class="btn btn-default"  ng-click="toggle(false)">Collapse All</span>
          <span class="btn btn-default"  ng-click="toggle(true)">Expand All</span>
      </div>
      <hr />
  </div>
</div>

JS:

var module = angular.module('plunker', []);

module.controller('AccordionDemo', ['$scope', 
  function ($scope) {
    $scope.results = [
      {label: 'Item 1', open: false},
      {label: 'Item 2', open: false},
      {label: 'Item 3', open: false}
    ];

    $scope.toggle = function(state) {
      $scope.results.forEach(function(e) {
        e.open = state;
      });
    }
  }
]);

see it working here: http://plnkr.co/edit/T6iv7mSoat9SQBwSIFJP

Upvotes: 4

dt0xff
dt0xff

Reputation: 1563

You have a problem with scopes. Simple rule is to never set variable value from ng-click or similar directives if you gonna use this variable outside - in parent.

It is caused by ng-repeat, which creates scope and if you will try to define new variable within it(you are doing it, because you have used name plunker, instead of opened), it will be defined only to current item in repeat.

You can use setter function to set it to right scope. So, here we go: http://plnkr.co/edit/h3MtKywiOaIQhpnAzWLT?p=preview

Upvotes: 0

Related Questions