respectTheCode respectTheCode - 1 year ago 88
AngularJS Question

What is the best way to conditionally apply a class?

Lets say you have an array that is rendered in a

with an
for each element and a property on the controller called
. What would be the best way to add a class to the
with the index
in AngularJS?

I am currently duplicating (by hand) the
code and adding the class to one of the
tags and using
to show only one
per index.

Answer Source

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 returns 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 kept CSS classes out of Controller code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download