Toggling accordion panel icons with ng-class and ng-click

Issue

I have an accordion with “chevron” icons that are toggled to point up or down when clicked, this is done with ng-click and ng-class. The accordion only permits one panel to be open at the same time – so when I click on a panel that is closed, the panel that is open closes. But how do I toggle the chevron icon on the open panel that is getting closed with ng-click?

Originally i could do it with DOM manipulation etc, but since this is a partial view in angular I cannot do it.

Code:

<div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" ng-click="firstpaneisopen=!firstpaneisopen">
           <i class="glyphicon" ng-class="{'glyphicon-chevron-up': firstpaneisopen, 'glyphicon-chevron-down': !firstpaneisopen}"></i> Collapsible Group Item #1
         </a>
      </h4>
     </div>
    <div id="collapseOne" class="panel-collapse collapse in">
     <div class="panel-body">
       Body
     </div>
    </div>
  </div>
  <div class="panel panel-default">
   <div class="panel-heading">
     <h4 class="panel-title">
       <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" ng-click="secondpaneisopen=!secondpaneisopen>
         <i class="glyphicon" ng-class="{'glyphicon-chevron-up': secondpaneisopen, 'glyphicon-chevron-down': !secondpaneisopen}"></i> Collapsible Group Item #2
       </a>
     </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse">
     <div class="panel-body">
       Body
     </div>
    </div>
   </div>
 </div>

Solution

I would recommend that you check out ‘UI Bootstrap’ from the AngularUI team. It’s a collection of “Bootstrap components written in pure AngularJS”.

http://angular-ui.github.io/bootstrap/

Their website features an example which shows their Accordion directive using ng-class to toggle the chevron icons.

http://angular-ui.github.io/bootstrap/#/accordion

Their directive also features a close-others attribute which, if true, will ensure only a single panel is open at any one time.

<accordion close-others="true">

Answered By – Andrew Sula

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.