AngularJS ng-class if-else expression

Dor Cohen picture Dor Cohen · Aug 11, 2013 · Viewed 536.5k times · Source

With AngularJS I'm using ng-class the following way:

<div class="bigIcon" data-ng-click="PickUp()" 
ng-class="{first:'classA', second:'classB', third:'classC', fourth:'classC'}[call.State]"/>

I'm wondering if I can use the if-else expression to do something similar to this:

<div class="bigIcon" data-ng-click="PickUp()" 
ng-class="{first:'classA', second:'classB', else:'classC'}[call.State]"/>

So whenever call.State differs from first or second use classC and avoid specifying each value?

Answer

Jossef Harush picture Jossef Harush · Feb 23, 2014

Use nested inline if-then statements (Ternary Operators)

<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">

for example :

<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
    ...
</div>

And make sure it's readable by your colleagues :)