Reputation:
I have a view, where I am using ng-repeat to populate a table content with dynamic data. Here's the code snippet-
<tr ng-repeat="x in response">
<td>{{x.property1}}</td>
<td>{{x.property2}}</td>
<td bgcolor="x.color1">{{x.property3}}</td>
<td bgcolor="x.color2">{{x.property4}}</td>
</tr>
But the table output is not changing. I am getting same color for every response. How do I actually alter the color? You can see the output in this Image. Also, the color that is present is not even supplied to the response.
How do I solve this?
Upvotes: 1
Views: 810
Reputation: 8301
Use ng-style
to change background color, With this you can bind any css style. please find documentation here: https://docs.angularjs.org/api/ng/directive/ngStyle
<tr ng-repeat="x in response">
<td>{{x.property1}}</td>
<td>{{x.property2}}</td>
<td ng-style="{'background-color': x.color1}">{{x.property3}}</td>
<td ng-style="{'background-color': x.color2}">{{x.property4}}</td>
</tr>
Please find the example below of how can you use ng-style
to set styles dynamically.
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.myName = {
name: 'Dummy name',
color1: 'white',
color2: 'tomato',
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller="ctrl" ng-app="app">
<p ng-style="{'background-color': myName.color2, 'color': myName.color1}">
{{ myName.name }}
</p>
</div>
Upvotes: 1
Reputation: 73906
You will need to use ng-style
directive for this like:
<tr ng-repeat="x in response">
<td>{{x.property1}}</td>
<td>{{x.property2}}</td>
<td ng-style="{'background-color': x.color1}">{{x.property3}}</td>
<td ng-style="{'background-color': x.color2}">{{x.property4}}</td>
</tr>
DEMO:
var app = angular.module('app', []);
app.controller('tableController', function($scope) {
$scope.response = [{
property1: 'Jill',
property2: 'Smith',
color1: 'red',
color2: 'green'
},
{
property1: 'John',
property2: 'Doe',
color1: 'yellow',
color2: '#336699'
},
];
});
table, td {
border: 1px solid black;
border-collapse: collapse;
}
td {padding: 10px; min-width:120px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table ng-controller="tableController" ng-app="app">
<tr ng-repeat="x in response">
<td ng-style="{'background-color': x.color1}">{{x.property1}}</td>
<td ng-style="{'background-color': x.color2}">{{x.property2}}</td>
</tr>
</table>
Upvotes: 3