Angular: Set Active CSS Class on Button Based on Function Return Value
Problem: Buttons have a different aesthetic when they’re set to active. Some may be colored blue and others look ‘depressed’ (pushed) to symbolize they’ve been activated. Dynamically allocating these CSS classes can be a pain – here are a few ways to go about it in AngularJS.
The first way to go about this is to give the button an AngularJS directive ng-model variable. ng-model tells the element that its value will be equal to the value of the variable you assigned to it. So you might have a variable that holds true or false based on whether or not the element should be active.
This can become unwieldy when you get to deeper application logic as you have to explicitly set that variable when you want the element to appear active. When you try to scale this technique to multiple elements, you’re forced to keep up with the state of multiple variables to show a few elements on the screen.
The AngularJS directive ng-class gives you the ability to add a CSS class to an element based on the value of a variable or function. The key part here is that it can rely on the return value of a function to apply a CSS class whereas ng-model can only be bound to a variable. This gives us a certain amount of abstraction from the variable juggling we had to do in the previous solution. It also gives you more control over what stylings are added based on different values.