Angular: How to change the color of cell table if condition is true
Asked Answered
E

3

9

I have an object which has a variable called changeColor. In my html table I want to change the cell color if changeColor is true. I am using angular.

    <tr ng-repeat="list in results">
    <% if (!{{list.changeColor}} ) %>
    <% { %>
        <td bgcolor="red">{{list.value}}</td>
    <% } %>
    <td>{{list.price}}</td>

But after testing it is always red and the <% if (! ) %> <% { %> <% } %> is written in my html page! Can you please help me?

Tested this

<td style=".red {bgcolor: red;} .black {bgcolor: black;}"
 ng-class='{red : list.changeColor, black: !list.changeColor}'>
 {{list.price}}</td>

But it does not work

Embolectomy answered 23/2, 2014 at 5:34 Comment(0)
R
27

You have to use ng-class

<tr ng-repeat="list in results">
    <td ng-class='{red : list.changeColor, black: !list.changeColor}'>{{list.value}}</td>
    <td>{{list.price}}</td>
</tr>

CSS

<style type="text/css">
.red {
    color: red; 
}

.black {
    color: black;
}
</style>
Rainbow answered 23/2, 2014 at 6:10 Comment(4)
Thanks Fizer Khan. How should .js file look like? I am new to angularEmbolectomy
You do not need to do anything on javascript. I guess, you only want to change the color by boolean flag.Rainbow
I did like this <td style=".red {bgcolor: red;} .black {bgcolor: black;}" ng-class='{red : list.changeColor, white: !list.changeColor}'>{{list.price}}</td> the output of inspect element in html is like ng-binding red which is correct but bgcolor is not changed why?Embolectomy
The inline style is wrong. You have to place it inside the style tag. I have updated the answer.Rainbow
H
6

Don't put so much logic in your views. Try this instead:

ngClass directive

It will allow you to change the td class based on an expression.

Hitherward answered 23/2, 2014 at 5:37 Comment(0)
C
0
 <td ng-class="{'negative':daily.MTDCompSales<0,'positive':daily.MTDCompSales>0}">{{daily.MTDCompSales | number:0}}</td>

This line of code changes based on data value, if data is positive or negative

Clinician answered 22/3, 2018 at 19:42 Comment(1)
css file- .negative{ background-color: red } .positive{ background-color: lime }Clinician

© 2022 - 2024 — McMap. All rights reserved.