I'm trying to figure out how to bind AngularJS scope vars into CSS syntax. I think that the problem is in the curly braces. Here is what I'm basically trying to do:
<style>.css_class {background:{{ angular_variable }}; color:#ffffff;}</style>
<style>.css_rule {background:{{ "#000000" }}; color:#ffffff;}</style>
<style>.css_rule {background:{{ var | someFilter }}; color:#ffffff;}</style>
Any ideas on how this could be accomplished? Thank you!
No, you can not use javascript variables inside css, but you can change the style of an element dynamically via javascript's DOM elements, style property.
create a new component and create a service to load dynamic css variables from API. Add style tag in template file and use variable values for properties. Load this template on all pages or on main template. On app build style will be moved to head tag.
The $ in AngularJs is a built-in object.It contains application data and methods.
The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.
As explained here angular doesn't run on content inside style tags. There's a workaround plunkr in that post but as a more flexible approach I'd just create a directive that grabs the contents, parses them and replaces:
app.directive('parseStyle', function($interpolate) {
return function(scope, elem) {
var exp = $interpolate(elem.html()),
watchFunc = function () { return exp(scope); };
scope.$watch(watchFunc, function (html) {
elem.html(html);
});
};
});
Usage:
<style parse-style>.css_class {color: {{ angular_variable }};}</style>
http://jsfiddle.net/VUeGG/31/
app.directive('parseStyle', function()
{
return function(scope, elem)
{
elem.html(scope.$eval('\'' + elem.html() + '\''));
};
});
then:
<style parse-style>.css_class {color: ' + angular_variable + ';}</style>
Not sure about the browser support for this though.
http://jsfiddle.net/VUeGG/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With