Reputation: 1140
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
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
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
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" }
}
}
Upvotes: 95