0

How can I change the background of a table cell dynamically in HTML using AngularJS ?

In the following code I want to show a table with a bunch of names and the including status of an object. The status can weather be VALID (green background) or INVALID (red background).

Can this problem be solved in my <td> HTML tag or do I have to move on to CSS ?

<table border="1">
   <tr ng-repeat="object in Cmd.items">
      <td>{{object.objectName}}</td>
      <td>{{object.objectStatus}}</td> //this background should be colored
   </tr>
</table>

4 Answers 4

2

You can do this using ng-class:

<tr ng-repeat="object in Cmd.items">
      <td>{{object.objectName}}</td>
      <td ng-class="{'red': object.objectStatus === 'invalid', 'green': object.objectStatus === 'valid'}">{{object.objectStatus}}</td> 
</tr>

Fiddle

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

Comments

1

you can use ng-class

e.x. :

<div ng-class={'green-bg':isValid, 'red-bg':!isValid}> </div>

green-bg and red-bg are css classes and isValid is property, where you know expression isValid or no

Comments

1

CSS :

.invalid{
background-color:red;
}

.valid{
background-color:green;
}

HTML

<table border="1">
   <tr ng-repeat="object in Cmd.items">
      <td>{{object.objectName}}</td>
      <td ng-class="object.objectStatus">{{object.objectStatus}}</td> //this background should be colored
   </tr>
</table>

Comments

0

It can be solved both in the td tag or/and in your external css.

In Html

     <td ng-style="{'background': (object.objectStatus=='VALID') ? 'green' : 'red'}">
        {{object.objectStatus}}
      </td>

With external css You can use @oto lolua implementation

Comments

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.