AngularJS ngClass conditional AngularJS ngClass conditional angularjs angularjs

AngularJS ngClass conditional


Your first attempt was almost right, It should work without the quotes.

{test: obj.value1 == 'someothervalue'}

Here is a plnkr.

The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here.If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

Just to complement: You can also use logical operators to form logical expressions like

ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"


Using ng-class inside ng-repeat

<table>    <tbody>            <tr ng-repeat="task in todos"                ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',              'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">                <td>{{$index + 1}}</td>                <td>{{task.name}}</td>                <td>{{task.date|date:'yyyy-MM-dd'}}</td>                <td>{{task.status}}</td>            </tr>    </tbody></table>

For each status in task.status a different class is used for the row.


Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.

Type 1

<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>

In this code class will be apply according to value of status value

if status value is 0 then apply class one

if status value is 1 then apply class two

if status value is 2 then apply class three


Type 2

<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>

In which class will be apply by value of status

if status value is 1 or true then it will add class test_yes

if status value is 0 or false then it will add class test_no