user1785730
user1785730

Reputation: 3525

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?

Upvotes: 1

Views: 185

Answers (3)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

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>

Upvotes: 1

forethought
forethought

Reputation: 3253

@shashank solution is good.

I always prefer to have logic part in controller or service. My solution would be like

$scope.getStyleCSS = function () {
    if ($scope.getValue() !== 0) {
        return 'alert-error';
    }
    return '';
}

$scope.getValue = function () {
    return $scope.value;
}

HTML

<span styleClass="getStyleCSS()" ng-bind="getValue()"></span>

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before Angular compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

Upvotes: 2

Sankar
Sankar

Reputation: 7107

Try this...

Make use of ng-class

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

Upvotes: 1

Related Questions