user1785730 user1785730 - 3 months ago 10
AngularJS Question

How to set an attribute conditionally in AngularJS

I have a

span
element displaying some value. If the value isn't 0, I want to apply some
styleClass
to the element:

<span styleClass="alert-error">{{value}}</span>


Otherwise, if the value is 0, I don't want to apply the
styleClass
. An empty
styleClass
attribute would be acceptable:

<span styleClass="">{{value}}</span>


How can I do this with AngularJS?

Answer

Here you go (just use the ternary operator):

<span styleClass="{{value == 0 ? '' : 'alert-error'}}">{{value}}</span>

Edit:

For class attribute just to the same like others have already mentioned:

<span class="{{value == 0 ? '' : 'alert-error'}}">{{value}}</span>

Also, you can use ng-class:

<span ng-class="{'alert-error': (value != 0)}">{{value}}</span>