Dor Cohen Dor Cohen - 3 months ago 62
AngularJS Question

angular ng-class if-else expression

I'm using angularjs ng-class at the following way:

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


and I wondered if I can use if-else expression, can I do something similar to this:

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


meaning whenever
call.State
different from
first
or
second
use
classC
and not specify each value.

thanks!

Answer

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 :)

Comments