user1785730 user1785730 - 1 year ago 117
AngularJS Question

How to set an attribute conditionally in AngularJS

I have a

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

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

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

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

How can I do this with AngularJS?

Answer Source

Here you go (just use the ternary operator):

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


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>