1

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.

3 Answers3

2

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}}">
Community
  • 1
  • 1
Michel
  • 26,600
  • 6
  • 64
  • 69
1
<tr ng-class="{'red': project.total <35  , 'yellow':project.total >= 35 && project.total<70,'green': project.total >= 70 } ">
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37
1

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')">
Michael Lorton
  • 43,060
  • 26
  • 103
  • 144