An Open/Closed Icon in Angular JS
A few examples of how to show that a panel is minimized

07 March 2015

I was helping a colleague with a problem he was trying to solve using Angular JS the other day. He was implementing an accordion effect, where clicking on a heading would show the panel beneath the heading. On the heading, there is an icon which points right if the panel is closed, and down if the panel is open.

The solution that he started with used a switch statement and looked something like this.

<span ng-switch="panel.closed">
    <i ng-switch-when="true" class="glyphicon glyphicon-chevron-right"></i>
    <i ng-switch-when="false" class="glyphicon glyphicon-chevron-down"></i>
</span>
First example

Improving this with ng-class

Using ng-switch works, but if you look at the two cases then you notice that the only difference between the two is the class indicating which icon to use. We can simplify this example by replacing the ng-switch with ng-class.

<span>
    <i ng-class="panel.closed ? 'glyphicon-chevron-right' : 'glyphicon-chevron-down'"
        class="glyphicon"></i>
</span>
Second example

I am lucky enough to only be supporting modern browsers

If you’re only supporting modern browsers, then you can take advantage of CSS3 properties. This lets us specify in out style sheet that if the icon has a ‘open-panel-icon’ class, then we want to rotate it. The cool thing about this approach is that we can combine it with the CSS3 transition property to animate changing from one icon to the next.

<span>
    <i ng-class="{'open-panel-icon': !panel.closed}"
        class="glyphicon glyphicon-chevron-right panel-icon" ></i>
</span>
Third example
.panel-icon {
  transition: transform 0.3s;
  transform: rotate(0deg);
}

.open-panel-icon {
  transform: rotate(90deg);
}

I’ve made a demo of these three approaches on Plunkr that you can play with here: Demo on Plunkr


If you liked this article, please share it on Twitter, Facebook, Google+, or by using the Permalink.


You can send me comments on this post at justin@worthe-it.co.za, or @JWorthe.


More on Worthe It

Previous Post

04 Jan 2015

Applying new experience to a language I haven't used in a long time
Next Post

12 Jun 2015

A brief introduction to the fundamentals
Latest Post

14 Aug 2017

A retrospective on a Rust audio signal processing program I wrote
Browse the Blog Archive

16 Dec 2014 - 14 Aug 2017

See all of the stuff I've written and put on this site.