AngularJS quick tip #1 : ng-class

Intro

The ng-class core directive makes dynamic css classes easy and straightforward.

In conjunction with ng-repeat, we can create dynamic HTML templates by choosing the right css class based on model attributes.

ng-class

The ng-class directive accepts a hash (javascript Object) where the keys are the names of the css classes that we want to append, and the values are booleans.

<div ng-repeat="item in items"  
     ng-class ="{ active: item.active, selected: item.selected }">

In the example above we are only including two classes, but the markup can get messy quickly (if not already).

Controller to the rescue

By definition, the angular controller should contain UI logic without coupling itself to the DOM. So it's best to implement a controller method that returns a hash based on our model:

class AppController {

    getStyle(item) {
        return {
            'active' : item.active,
            'selected' : item.selected
        }        
    }
}

Now, in the HTML we can replace our inline object with the function that we wrote above:

<div ng-repeat="item in items"  
     ng-class ="getStyle(item)">

It's much easiear to maintain an object on the controller level than an inline object that we keep in our markup.