I would like to apply a background-color
with ng-style
conditionally when the color value can be updated from $scope
.
Here are my variables in scope:
$scope.someone = { id: '1', name: 'John', color: '#42a1cd' };
$scope.mainId = 1;
Actually I don't use any condition to apply the background color, it is done with:
<div ng-style="{'background-color': someone.color}">
{{someone.name}}
</div>
The idea here is to apply this background color only when someone.id == mainId
. I tried several solutions, but it does not seems to be the correct synthax:
ng-style="{{someone.id == mainId}} ? ('background-color': {{someone.color}}) : null"
ng-style="{ ('background-color': someone.color) : someone.id == mainId }"
Does someone have an idea of how I can achieve this?
You may try like this
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-style="{'background-color': getColor(someone)}">
{{someone.name}}
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.someone = {
id: 1,
name: 'John',
color: '#42a1cd'
};
$scope.getColor = function(someone) {
if($scope.mainId === someone.id) {
return someone.color;
}
}
$scope.mainId = 1;
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With