Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AngularJs "ng-style" within "ng-repeat" iteration

I am tring to conditionally set the colors of data elements in a table based on their value using ng-style. Each row of data is being generated using ng repeat.

So i have something like:

<tr ng-repeat="payment in payments">   <td ng-style="set_color({{payment}})">{{payment.number}}</td> 

and a function in my controller that does something like:

$scope.set_color = function (payment) {   if (payment.number > 50) {     return '{color: red}'   } } 

I have tried a couple different things. and even set the color as a data attribute in the payment object, however it seems I cant get ng-style to process data from the data bindings, Does anyone know a way I could make this work? Thanks.

like image 682
Sean Geoffrey Pietz Avatar asked Apr 19 '13 19:04

Sean Geoffrey Pietz


People also ask

What is the use of NG-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object.

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

Does ng-repeat create a new scope?

Directives that Create Scopes In most cases, directives and scopes interact but do not create new instances of scope. However, some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element.


2 Answers

Don't use {{}}s inside an Angular expression:

<td ng-style="set_color(payment)">{{payment.number}}</td> 

Return an object, not a string, from your function:

$scope.set_color = function (payment) {   if (payment.number > 50) {     return { color: "red" }   } } 

Fiddle

like image 60
Mark Rajcok Avatar answered Sep 23 '22 07:09

Mark Rajcok


use this code

<td style="color:{{payment.number>50?'red':'blue'}}">{{payment.number}}</td> 

or

<td ng-style="{'color':(payment.number>50?'red':'blue')}">{{payment.number}}</td> 

blue color for example

like image 25
Behnam Mohammadi Avatar answered Sep 22 '22 07:09

Behnam Mohammadi