Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 405
Luis Avatar asked Jan 24 '15 13:01

Luis


1 Answers

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.

like image 142
Shomz Avatar answered Oct 13 '22 13:10

Shomz