Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind AngularJS variables into CSS syntax

Tags:

css

angularjs

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!

like image 764
dcohenb Avatar asked Aug 15 '13 07:08

dcohenb


People also ask

Can you use Javascript variables in css?

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.

How do I add dynamic css in angular 6?

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.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

What is Ngbind?

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.


1 Answers

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:

Updated answer

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/


Original answer

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/

like image 94
noj Avatar answered Sep 21 '22 23:09

noj