Sean Geoffrey Pietz
Sean Geoffrey Pietz

Reputation: 1140

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.

Upvotes: 37

Views: 65052

Answers (3)

Anil Singh
Anil Singh

Reputation: 4212

It might help you!

<!DOCTYPE html>
<html>

<head>
  <style>
    .yelloColor {
      background-color: gray;
    }
    .meterColor {
      background-color: green;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script>
    var app = angular.module('ngStyleApp', []);
    app.controller('ngStyleCtrl', function($scope) {
      $scope.bar = "48%";
    });
  </script>
</head>

<body ng-app="ngStyleApp" ng-controller="ngStyleCtrl">
  <div class="yelloColor">
    <div class="meterColor" ng-style="{'width':bar}">
      <h4> {{bar}} DATA USED OF 100%</h4>
    </div>
  </div>
</body>

</html>

Upvotes: 3

Behnam
Behnam

Reputation: 6459

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

Upvotes: 21

Mark Rajcok
Mark Rajcok

Reputation: 364697

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

Upvotes: 95

Related Questions