2

I am just beginning using Angular JS in my project.

I have been searching for a way to change the background color from a HTML table cell depending on the value of an Angular JS expression, but haven't found the solution yet.

This is the cell:

<td>{{data.material_or_service}</td>

Any help is welcome

1
  • 2
    see ng-class which allows you to set a class to a DOM element with condition Commented Dec 31, 2015 at 23:50

1 Answer 1

4

You should use ng-class : https://docs.angularjs.org/api/ng/directive/ngClass

Example:

css:

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

angular view:

<td ng-class="{'red': (variable == 1), 'blue': (variable ==2)}">{{data.material_or_service}</td>

EDIT:

Try that first:

<div ng-class="{'red' : (test != null)}">
  hey !
</div>

<div ng-class="{'red' : (test == null)}">
  hey 2 !
</div>

and set up .red { background-color: red; } in the css. Hey2 is supposed to be in red.

EDIT 2:

Now try with :

<table>
<tr>
<td ng-class="{'red' : (test == null)}">
  hey !
</td>
</tr>
</table>

The <td> is red.

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

10 Comments

Thank you Pierre, and instead of variable? I am trying as follows: <td ng-class="{red: (material_or_service == 1), blue: (material_or_service ==2)}">{{data.material_or_service}}</td> and nothing changes, only the value for {{data.material_or_service}} is shown
@mvasco: I updated the post to give you an example to insert in the code to allow you to test with <div> . The problem is that I failed, it's 'red' and not red in the ng-class ... (my bad, sorry) . In the js console you should have had an error.
But not the line: <td ng-class="{'red': (material_or_service == 1), 'blue': (material_or_service ==2)}">{{data.material_or_service}}</td>
@mvasco: edited to add the 2nd try: it works for a td, so I bet material_or_service has a wrong value. Try to put a {{ material_or_service | json }} before your <table>, to see its value.
Checked and the value is "1", as expected.
|

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.