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

Sean Geoffrey Pietz picture Sean Geoffrey Pietz · Apr 19, 2013 · Viewed 63.7k times · Source

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.

Answer

Mark Rajcok picture Mark Rajcok · Apr 19, 2013

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