ngStyle is the directive used to set inline style attributes with AngularJs. Most of the time, it’s straightforward to use.
background css attributes can be just slightly trickier.
ngStyle directive requires an object for input. The object key is the css attribute name. The resultant value for the key is the value of the css attribute.
ngStyle is obviously used to set dynamic styles, because static styles are more easily and efficient set using the standard html
A Dynamic Style Example
So let’s setup a controller that sets a dynamic color based on something as useful as the time. Useful, right?
1 2 3
We could use this
getColor function in our app:
1 2 3 4 5 6
A Background Example
If we have a dynamic value that needs to go in a css
background-image attribute, it can be just a bit more tricky to specify.
Let’s say we have a
getImage() function in our controller. This function returns a string formatted similar to this:
url(icons/pen.png). If we do, the
ngStyle declaration is specified the exact same way as before:
Make sure to put quotes around the
Another Background Example
That example was easy. Often, however, you don’t have data stored in your models that’s formatted like
1 2 3 4