angularjsangular-uiangular-ui-bootstrapangular-bootstrap

Angularjs Accordion Access isOpen State


Is there a way to access whether an accordion-group is open or not? I know there's the isOpen directive but I'm not sure if there's a way to access the state of that while purely in the html. Using (and abusing?) two way binding I can set a variable to hold that state but it will not work out for nested accordions without doing something like isOpen0, isOpen1, isOpen2, etc. I can also use ng-init to "declare" a new isOpen on the scope of the nested accordions but that doesn't sound like a good idea.

  <accordion>
    <accordion-group is-open="isOpen">
      <accordion-heading>
         <div ng-class="{'myClass': isOpen}">Static Text</div>
      </accordion-heading>
      This content is straight in the template.
    </accordion-group>
  </accordion>

http://plnkr.co/edit/l5y4raei99pedNWcE225


Solution

  • First, you have to use a parent object like in Angular UI's docs' example, status object for example:

      <div accordion-group="" ng-init="status = {isOpen: false}" is-open="status.isOpen">
          <div accordion-heading="">
              <div ng-class="{'is-open': status.isOpen}">NUTRIENT PROFILES</div>
          </div>
          ...
      </div>
    

    Then, you can perfectly use the same object name for nested accordion. Reason is simple: accordion-group directive will instantiate a new scope for each group. This way, when a status.isOpen is changed, it won't affect other groups.

    Check it: http://plnkr.co/edit/nJ654pvE1itnGDQGp2rk?p=preview