Set Background Colour with AngularJS

From the “I can’t believe I had to look it up” department:

One can use ngStyle to programmatically set the background colour of an element. This is arbitrary ugly code that demonstrates the concept:

[html light=”true”]
<span ng-style="{background: item.color}">
[/html]

The “gotcha” is if one wishes to only use this on a certain page, one must reset the colour when the controller’s $scope is destroyed:

[javascript]
$scope.$on("$destroy", function(){
    $("body").css(‘background-color’, ‘white’);
});
[/javascript]

Leave a Reply