0

I'm rendering data in a table using Angular and ng-repeat. What I would like to do is add an if condition to say if the value contained in ng-repeat is a certain word, set the background colour of that row to red. I think it might look something like this, but I'm not sure how to do this in Angular.

if( {{field.value}} == THING){
var backgroundColour = red;
}

I was thinking of using ng-filter, although I dont wan't to actually filter the data, just set a variable based on a value.

Any ideas?

4 Answers 4

3

You could add an ng-class in the html to achieve this.

<div ng-repeat"field in fields" ng-class="{'with-background': field.value == THING}">
    {{field.value}}
</div>

And then add with-background to css

.with-background {
    background-color: red;
}

If THING is a variable pointing to some other value, you don't have to use quotes and if it's meant to be a string, use it as 'THING'

Here's the official documentation of ngClass: https://docs.angularjs.org/api/ng/directive/ngClass

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

3 Comments

Thanks, so I'm pulling field.value from ng-repeat, so when I use it in my table I use {{field.value}}. To use your example should I use {{field.value}} == THING, or just field.value without the {{}}? Also, should THING be quoted?
you don't have to use {{}} and I don't know what thing is, if it's a variable, don't use ' ' and if it's meant to be a string, use the quotes.
Thanks, I was using double quotes for the field.value == "THING" when I should have been using single quotes! I changed to field.value == 'THING' and It's working now!
1

You cann also use ng-style for this

<div ng-style="field.value == THING?{'background-color':'red'}:{}">
    Hello Plunker!
</div>

plunker

Comments

1

You could do something like this below:

<div ng-repeat="field in collections" 
         ng-if="field.value && field.value =='THING'">
      {{backgroundcolor}}
</div>

Or you could you use ng-class directive

<div id="wrap" ng-class="{true: 'yourClassName'}[field.value]">

Comments

0

You can use ng-class directive

<tr ng-class="{'color-red': item.value > 0}" ng-repeat="item in vm.items">
    <td>{{ item.value }}>/td>
</tr>

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.