A Dev
A Dev

Reputation: 321

Angular if condition from value of ng-repeat

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?

Upvotes: 0

Views: 1602

Answers (4)

Chanthu
Chanthu

Reputation: 1794

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

Upvotes: 3

Thalaivar
Thalaivar

Reputation: 23632

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]">

Upvotes: 1

AntiHeadshot
AntiHeadshot

Reputation: 1130

You cann also use ng-style for this

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

plunker

Upvotes: 1

Mike Kor
Mike Kor

Reputation: 876

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>

Upvotes: 0

Related Questions