Change background color with ng-Style

How to change background color using ng-style?

this div will be repeated so that one of the colors is from the database. For plnkr, I just set the colors, but in my example it 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

+5
source share
3 answers

You cannot make ternary conditions in a tag, and you have a mistake since you did not specify background-color . You must either quote it or use camelCase, while the conditions must be set in the controller.

So, the fix should have a scope variable denoting the color (or the full style object) and use it as follows: http://plnkr.co/edit/iYkSa2I1ysZutdkAKkuh?p=preview


UPDATE

Here is an example that you could use to make your code work with your database (here I call external JSON, but the principle is the same): http://plnkr.co/edit/Kegs95NNyGGySMDzhQed?p=preview

This way you can also select the β€œselected” color. That’s almost all I can tell you with the information you provided.

+3
source

Both are different styles. Using:

 return {backgroundImage:'URL'}; 

or

 return {backgroundColor:'Color'}; 
0
source

Youse:

 return {backgroundImage:'someimg'}; 
-1
source

Source: https://habr.com/ru/post/1211824/


All Articles