How can i change the background color with ng-style?
this Div gonna repeat so the one of the color is from DB. For the plnkr i just fixed the colors, but in my example is like this:
<div class="col-md-offset-0 col-md-2" ng-repeat="type in types" style="margin-bottom:5px;">
<div class='container' divCheckbox ng-style="{'background-color':(isSelected?'{{type.color}}':'#ccc')}>
<input type='hidden' ng-model="type.show" />
<div class="label">{{type.name}}</div>
</div>
</div>
And the directive:
.directive('divCheckbox', function () {
return {
restrict: 'A',
link: function (scope, el, attr) {
scope.isSelected = el.find('input').val() == 'false';
el.on('click', function () {
scope.isSelected = !scope.isSelected;
scope.$apply();
});
}
}
});
Heres my plnkr: http://plnkr.co/edit/onLA8vSbtwQu1OxZrKzT?p=preview
You can't do ternary conditions within a tag and you have an error since you didn't quote background-color
. You have to either quote it, or use camelCase, while the conditions should be set in the controller.
So, the fix is to have a scope variable denoting a color (or the full style object) and use it like this: http://plnkr.co/edit/iYkSa2I1ysZutdkAKkuh?p=preview
UPDATE
Here's an example you could use to make your code work with your DB (I'm calling external JSON here, but the principle is the same): http://plnkr.co/edit/Kegs95NNyGGySMDzhQed?p=preview
This way you could fetch the 'selected' color as well. That's pretty much all I can tell you with the info you provided.
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