将AngularJS变量绑定到CSS语法中

dco*_*enb 16 css angularjs

我试图弄清楚如何将AngularJS范围变量绑定到CSS语法中.我认为问题在于大括号.这是我基本上要做的事情:

<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>
Run Code Online (Sandbox Code Playgroud)

关于如何实现这一点的任何想法?谢谢!

noj*_*noj 23

如此处所解释的, angular不会在样式标记内的内容上运行.在该帖子中有一个变通方法,但作为一种更灵活的方法,我只需创建一个抓取内容的指令,解析它们并替换:

更新的答案

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);
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

用法:

<style parse-style>.css_class {color: {{ angular_variable }};}</style>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/VUeGG/31/


原始答案

app.directive('parseStyle', function()
{
    return function(scope, elem)
    {
        elem.html(scope.$eval('\'' + elem.html() + '\''));
    };
});
Run Code Online (Sandbox Code Playgroud)

然后:

<style parse-style>.css_class {color: ' + angular_variable + ';}</style>
Run Code Online (Sandbox Code Playgroud)

虽然不确定浏览器对此的支持.

http://jsfiddle.net/VUeGG/4/