This should be a simple problem, but I can't seem to find a solution.
I have the following markup:
<div style="width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:#ff0000;"></div>
I need the background color to be bound to the scope, so I tried this:
<div style="{width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:{{data.backgroundCol}};}"></div>
That didn't work, so I did some research and found ng-style
, but that didn't work, so I tried taking the dynamic part out and just hard-coding the style in ng-style
, like this...
<div ng-style="{width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:#ff0000;}"></div>
and that doesn't even work. Am I misunderstanding how ng-style
works? Is there a way of putting {{data.backgroundCol}}
into a plain style attribute and getting it to insert the value?
Directly from
ngStyle
docs:So you could do this:
Hope this helps!
I would say that you should put styles that won't change into a regular
style
attribute, and conditional/scope styles into anng-style
attribute. Also, string keys are not necessary. For hyphen-delimited CSS keys, use camelcase.ngStyle directive allows you to set CSS style on an HTML element dynamically.
ng-style="{color: myColor}"
Your code will be:
If you want to use scope variables:
Here an example on fiddle that use
ngStyle
, and below the code with the running snippet:On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.
The easiest way is to call a function for the style, and have the function return the correct style.
And in your controller: