What is the best way to conditionally apply a class?

Solution 1:

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.

Solution 2:

ng-class supports an expression that must evaluate to either

  1. A string of space-delimited class names, or
  2. An array of class names, or
  3. A map/object of class names to boolean values.

So, using form 3) we can simply write

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

See also How do I conditionally apply CSS styles in AngularJS? for a broader answer.


Update: Angular 1.1.5 has added support for a ternary operator, so if that construct is more familiar to you:

ng-class="($index==selectedIndex) ? 'selected' : ''"

Solution 3:

My favorite method is using the ternary expression.

ng-class="condition ? 'trueClass' : 'falseClass'"

Note: Incase you're using a older version of Angular you should use this instead,

ng-class="condition && 'trueClass' || 'falseClass'"

Solution 4:

I'll add to this, because some of these answers seem out of date. Here's how I do it:

<class="ng-class:isSelected">

Where 'isSelected' is a javascript variable defined within the scoped angular controller.


To more specifically address your question, here's how you might generate a list with that:

HTML

<div ng-controller="ListCtrl">  
    <li class="ng-class:item.isSelected" ng-repeat="item in list">   
       {{item.name}}
    </li>  
</div>


JS

function ListCtrl($scope) {    
    $scope.list = [  
        {"name": "Item 1", "isSelected": "active"},  
        {"name": "Item 2", "isSelected": ""}
    ]
}


See: http://jsfiddle.net/tTfWM/

See: http://docs.angularjs.org/api/ng.directive:ngClass