What is the best way to conditionally apply a class?

If you don’t want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:

ng:class="{true:'selected', false:''}[$index==selectedIndex]"

Please note the old syntax with colon.

There is also a new better way of applying classes conditionally, like:

ng-class="{selected: $index==selectedIndex}"

Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.

However these ways are not functionally equal. Here is an example:

ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"

We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.

Leave a Comment