Sunday 12 October 2014

Programatically Set Inline Styles for an Element

A few months ago I wrote a directive that had a requirement to be somewhat responsive. In order to achieve this I needed to change the width of an inner element. I also wanted to style up different parts of the component dependant upon certain conditions. As a result I had to use ng-style.


To use programatic inline styles you need to use ng-style in your html:

<div ng-style="divStyling"></div>

In the above, divStyling needs to be set on the $scope in any controller that has scope over this html. AngularJs is expecting your variable to be an object, so you should write it like the following:

divStyling = {
    width: 100px,
    color: 'red',
    position: 'fixed'
};


There is a bit of a gotcha here when you try to do things programatically. The object does not like concatenation to happen with the object assignment. If you want to create the width with an equation and then add px to it, you must assign this into a variable and then use that variable within the object.

var newWidth = someCalculatedValue + 'px',
divStyling = {
    width: newWidth,
    color: 'red',
    position: 'fixed'
};


This is the same for anything that requires a concatenation; you'll need to create a new variable with the concatenated value before using it in your object assignment.

No comments:

Post a Comment