2

I want to change the background color of a couple of divs based on the choosen color from a colorpicker.

I have tried it using this:

<div ng-style="[id^='color']{background-color: '{{rgbPicker.color}} !important}'">
    <div bind-html-compile="body">
        <div id="color1"></div>
        <div id="color2"></div>
        <div id="color3"></div>
        <div id="color4"></div>
    </div>
</div>

I have the right color code in rgbPicker.color (hex code), but the color is not changing. How can I make this work?

4
  • 2
    maybe add # before the color value Commented Dec 22, 2017 at 9:13
  • @TemaniAfif the # is already added by the colorpicker. Commented Dec 22, 2017 at 9:40
  • ng-style="{'background-color':'{{rgbPicker.color}}'}"> Commented Dec 22, 2017 at 9:40
  • I don''t think so that you need add selector for 'ng-style'. You should type: <div ng-style="{background-color: '{{rgbPicker.color}} !important}'">. If rgbPicker.color is in hex mode then you should use: <div ng-style="{background-color: '#{{rgbPicker.color}} !important}'">. Commented Dec 22, 2017 at 9:41

1 Answer 1

1

Do you really need / want to go through the ngStyle directive, when all you want is to set a background color? Here is a dead simple example using the default <input> color picker which updates the <body> background in a $watch :

<input type="color" ng-model="color">
$scope.color = '#ffffff'
var body = document.querySelector('body');  
$scope.$watch('color', function(newVal) {
  body.style.backgroundColor = newVal
})

http://plnkr.co/edit/jdWdaqejBLb1hjXF680f?p=preview

You can replace <body> with any querySelectable' element.

Sign up to request clarification or add additional context in comments.

1 Comment

nice! That works! Created an var divs = queryselectorAll('[id^='color']') and a loop [].forEach.call(divs, function(div){ }) through the found divs to change the color with div.style['background-color'] = $scope.rgbPicker.color

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.