Luis
Luis

Reputation: 2715

Change background color with ng-Style

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

Upvotes: 9

Views: 72063

Answers (3)

Vishnu T Asok
Vishnu T Asok

Reputation: 244

Both are different styles. Use:

return {backgroundImage:'URL'};

or

return {backgroundColor:'Color'};

Upvotes: 1

Yishai Stern
Yishai Stern

Reputation: 39

youse:

return {backgroundImage:'someimg'};

Upvotes: -1

Shomz
Shomz

Reputation: 37691

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.

Upvotes: 5

Related Questions