How to set multiple conditions to style in angularjs

I have a table. I want to set different colors depending on the values of one of the columns. I have managed to set two colors using NgClass. But how can I set three different conditions.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<tr ng-class="{{project.total >= 0}} ? 'danger':'success'">

  <td>
    {{project.total}}

  </td>
</tr>
I want three conditions, if total is less than 35, color should be red, between 35 and 70 ; yellow and above 70 should be green. How can i do this with angular. I am very new to angular.

Upvotes: 1

Views: 316

Answers (3)

Michel
Michel

Reputation: 28349

You can pass an object as a value of ng-class.

From the documentation :

If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name.

Your object will be something like that :

{
    'red': project.total < 35,
    'yellow': project.total >= 35 && project.total < 70,
    'green': project.total >= 70
}

Therefore, your html is :

<tr ng-class="{ 'red': project.total < 35, 'yellow': project.total >= 35 && project.total < 70, 'green': project.total >= 70 }">

Edit: See demo fiddle

However, because of angular's digest mechanism you should keep only simple conditions in your templates. The resulting class computation could be deported in the controller, and you would have only :

<tr ng-class="{{project.class}}">

Upvotes: 2

Michael Lorton
Michael Lorton

Reputation: 44436

Really, you should do work this complicated in a controller rather than the HTML, but if you insist, you could do this:

<tr ng-class="project.total < 35 ? 'danger': (project.total < 71 ? 'partial' : 'success')">

Upvotes: 1

Srinath Mandava
Srinath Mandava

Reputation: 3462

<tr ng-class="{'red': project.total <35  , 'yellow':project.total >= 35 && project.total<70,'green': project.total >= 70 } ">

Upvotes: 1

Related Questions