0

I'm fetching data using a REST API and one of the attributes returned can be any of 3 options;

The options are; Negative, Warning, Success.

I want to set a class using ng-class based on the value returned;

I'm able to do this but only for one; Code below;

<div class="alert" ng-class="restaurantNotice(restaurant[0].notice)" ng-if="restaurant[0].notice.length">
    <div class="alert-inner inner-large" ng-bind="restaurant[0].notice"></div>
</div>

$scope.restaurantNotice = function(a) {
    return (a = Negative) ? 'negative' : '';
};

As you can see, if a = Negative then a class negative is applied else nothing is applied.

Now I want to check for all three options and apply 3 different classes respectively

moh_abk
  • 2,064
  • 7
  • 36
  • 65

4 Answers4

1

Instead of function in ng-class, use object

ng-class="{'negative' : restaurant[0].notice == 'Negative', 'warning' : restaurant[0].notice == 'Warning', 'success' : restaurant[0].notice == 'Success'}"
varun
  • 652
  • 4
  • 5
0

In this way:

<p ng-class="{a: deleted, b: important, c: error}">Example</p>

if a is true, apply class deleted, and so on.

Serginho
  • 7,291
  • 2
  • 27
  • 52
0

You can try

<div class="alert" ng-class="{'negative' : restaurant[0].notice.length, 'warning' : restaurant[1].notice.length, 'success' : restaurant[2].notice.length}">
    <div class="alert-inner inner-large" ng-bind="restaurant[0].notice"></div>
</div>

duplicate of Adding multiple class using ng-class

Community
  • 1
  • 1
vpsingh016
  • 703
  • 5
  • 9
0

If you are just going to set the same notice type (Negative, Warning, Success) as class then just convert to lower case and return from the function instead of putting conditions.

$scope.restaurantNotice = function(a) {
    return a.toLowerCase();
};

OR

<div class="alert" class="{{restaurant[0].notice | lowercase}}" ng-if="restaurant[0].notice.length">
Siva
  • 2,735
  • 16
  • 14