1

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?

3
  • I'm curious, if you are trying to apply an attribute named styleClass or you are trying to apply the class attribute. Commented Aug 10, 2016 at 12:26
  • styleClass actually comes from jsf, which I don't need anymore now that I'm going for AngularJS. So it's in fact the class attribute I want to apply. Commented Aug 10, 2016 at 12:44
  • yup! see my updated answer Commented Aug 10, 2016 at 12:44

3 Answers 3

2

@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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

Try this...

Make use of ng-class

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

1 Comment

It seems like there is something missing. This is the resulting code: <span class="ng-binding" ng-class="alert-error">5</span>. And the style is NOT applied.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.