绑定变量AngularJS到CSS语法 [英] Bind AngularJS variables into CSS syntax

查看:950
本文介绍了绑定变量AngularJS到CSS语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何绑定AngularJS范围瓦尔到CSS语法。
我认为这个问题是在大括号内。
这里是我基本上试图做的:

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!

推荐答案

按如下说明 角不上的风格标签中的内容执行。有一个变通方法plunkr在该职位,但作为一个更灵活的方法我刚刚创建,抓住内容,解析它们并取代了指令:

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);
        });
    };
});

用法:

<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() + '\''));
    };
});

然后

<style parse-style>.css_class {color: ' + angular_variable + ';}</style>

不知道有关这虽然浏览器的支持。

Not sure about the browser support for this though.

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

这篇关于绑定变量AngularJS到CSS语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆