将 AngularJS 变量绑定到 CSS 语法中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18248437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:57:46  来源:igfitidea点击:

Bind AngularJS variables into CSS syntax

cssangularjs

提问by dcohenb

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:

我试图弄清楚如何将 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>

Any ideas on how this could be accomplished? Thank you!

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

回答by noj

As explained hereangular 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:

正如这里所解释的angular 不会在样式标签内的内容上运行。在那篇文章中有一个解决方法 plunkr 但作为一种更灵活的方法,我只是创建一个指令来获取内容,解析它们并替换:

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/

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/

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

回答by Campbeln

Update

更新

I've put together an Angular "plugin" (module+filters+factory) called ngCssthat handles this and much more - check it out!

我已经组合了一个名为 ngCss的 Angular“插件”(模块+过滤器+工厂)来处理这个以及更多 -检查它

I also have made a Vanilla Javascript (e.g. no external dependencies) version as well; CjsSS.js(GitHub).

我还制作了一个 Vanilla Javascript(例如没有外部依赖项)版本;CjsSS.js( GitHub)。

ngCssis a tiny* Angular Module+Factory+Filters that enables binding of strings and objects (including nested objects) within CSS. *Minified+compressed script under 1,700 bytes

Features:

  • CSS can be live-bound (changes in $scopeare $watch'ed) or updated via the custom $broadcastevent updateCss.
  • css and cssInline Filters output Javascript/JSON objectsas CSS to enable mixins, including the ability to nest objects.
  • $scopecan be initialized within the CSS itself, allowing for all CSS-related information to be co-located within the *.css or STYLE element.
  • $scopecan be isolated or imported from any Angular $element(via angular.element($element).scope()).

ngCss是一个微小的* Angular Module+Factory+Filters,它支持在 CSS 中绑定字符串和对象(包括嵌套对象)。* 1,700 字节以下的最小化+压缩脚本

特征:

  • CSS 可以是实时绑定的(更改$scope$watch'ed)或通过自定义$broadcast事件 updateCss更新。
  • css 和 cssInline 过滤器将 Javascript/JSON 输出objects为 CSS 以启用 mixins,包括嵌套objects.
  • $scope可以在 CSS 本身内初始化,允许所有与 CSS 相关的信息位于 *.css 或 STYLE 元素中。
  • $scope可以从任何 Angular 中隔离或导入$element(通过angular.element($element).scope())。

OriginalThanks to @jonnyynnoj's code I've figured out a way to keep the {{angular_variable}}nomenclature within the style tags as well as live binding any changes. Check out the fork of @jonnyynnoj's codefor a simple example or have a look below at what I'm using in my apps:

原创感谢@jonnyynnoj 的代码,我找到了一种方法来将{{angular_variable}}命名法保留在样式标签中,并实时绑定任何更改。查看@jonnyynnoj 代码的分支以获得一个简单的示例,或者在下面查看我在我的应用程序中使用的内容:

(function (ngApp) {
    'use strict';

    //# Live bind a <style cn-styler="{ commented: true, usingSingleQuote: true }" /> tag with {{ngVars}}
    ngApp.directive('cnStyler', function () {
        return {
            //# .restrict the directive to attribute only (e.g.: <style cn-styler>...</style>)
            restrict: "A",
            link: function ($scope, $element, $attrs, controllers) {
                //# .$eval the in-line .options and setup the updateCSS function
                //#     NOTE: The expected string value of the inline options specifies a JSON/JavaScript object, hence the `|| {}` logic
                var css, regEx,
                    options = $scope.$eval($attrs["cnStyler"]) || {},
                    updateCSS = function () {
                        //# .$eval the css, replacing the results back into our $element's .html
                        $element.html($scope.$eval(css));
                    }
                ;

                //# Setup the .quote and the inverse in .unquote (which we use to process the css)
                //#     NOTE: In theory, the .unquote should not be present within the css
                options.quote = (options.usingSingleQuote !== false ? "'" : '"');
                options.unquote = (options.quote === '"' ? "'" : '"');
                regEx = new RegExp(options.unquote, "g");

                //# Process the $element's .html into css, .replace'ing any present .unquote's with .quote's (this could cause problems), then the {{Angular}} (or /*{{Angular}}*/) variables with ' + stringified_versions + '
                if (options.commented !== false) {
                    css = options.unquote + ($element.html() + '')
                        .replace(regEx, options.quote)
                        .replace(/\/\*{{/g, options.unquote + "+")
                        .replace(/}}\*\//g, "+" + options.unquote)
                    + options.unquote;
                } else {
                    css = options.unquote + ($element.html() + '')
                        .replace(regEx, options.quote)
                        .replace(/{{/g, options.unquote + "+")
                        .replace(/}}/g, "+" + options.unquote)
                    + options.unquote;
                }

                //# .$watch for any changes in the $scope, calling our updateCSS function when they occur
                $scope.$watch(updateCSS);
            }
        };
    });

})(YOUR_NG_APP_VAR_HERE);

Then you use this directive like this:

然后你像这样使用这个指令:

<style cn-styler type="text/css">
    .myClass{
        color: /*{{themeColor}}*/;
    }
</style>

Where you have set $scope.themeColorsomewhere in your controller and you've replaced YOUR_NG_APP_VAR_HEREwith your ngAppvariable.

$scope.themeColor在控制器中的某处设置并替换YOUR_NG_APP_VAR_HEREngApp变量的位置。

NOTES:

笔记:

Make sure that your ng-controlleris defined with scope to the <style>tag as <style>tag's should be in the <head>while ng-controlleris generally defined on the <body>tag or below. TL;DR:Put your ng-controlleron your <html>tag like so:

确保您ng-controller定义了<style>标签的范围,因为<style>标签应该在<head>whileng-controller通常定义在<body>标签上或下面。TL;DR:像这样把你ng-controller<html>标签放在你的标签上:

<html ng-app="YOUR_NG_APP_VAR_HERE" ng-controller="MyNgController">

Due to CSS parsing and auto-formatting in tools like Visual StudioI added the feature to have the {{Angular}}vars within CSS comments (e.g. /*{{Angular}}*/). This is the default behaviorof the directive unless you override it like so:

由于在Visual Studio等工具中进行 CSS 解析和自动格式化,我添加了{{Angular}}在 CSS 注释中包含变量的功能(例如/*{{Angular}}*/)。这是指令的默认行为,除非您像这样覆盖它:

<style cn-styler="{commented: false}" >...</style>

Due to the nature of this solution (the CSS is .$evaluated as a string with variables inserted within), the presence of single or double quotes within the CSS also needs to be processed. By default, the directive assumes you are using single quotes (') within your CSS which means in order to avoid any introduced errors you should only use single quotes within your CSSas any double quotes present within the CSS will be replaced with single quotes. You can override this default behavior (meaning you're using double quotes within your CSS) like so:

由于此解决方案的性质(CSS 被.$eval用作其中插入了变量的字符串),还需要处理 CSS 中存在的单引号或双引号。默认情况下,该指令假定您在 CSS 中使用单引号 ('),这意味着为了避免任何引入的错误,您应该只在 CSS 中使用单引号,因为CSS中存在的任何双引号都将被替换为单引号。您可以覆盖此默认行为(意味着您在 CSS 中使用双引号),如下所示:

<style cn-styler="{usingSingleQuote: false}" >...</style>

There are edge cases where the replacing of double quotes with single quotes screws up the CSS (such as in content), so you will want to ensure that you are only using one style of quotes in your CSS (and signaling the directive accordingly) to avoid any potential issues. Thankfully quotes are rarely used in CSS so this is mostly a non-issue.

在某些边缘情况下,用单引号替换双引号会破坏 CSS(例如 in content),因此您需要确保在 CSS 中仅使用一种样式的引号(并相应地向指令发出信号)以避免任何潜在的问题。谢天谢地,CSS 中很少使用引号,所以这基本上不是问题。

回答by Matthew Tyler

You shouldn't need the curly braces as these are being evaluated inside html directive - you only need to use the curly braces if you have an expression that is evaluated outside of them ie;

您不应该需要花括号,因为它们是在 html 指令中计算的 - 如果您有一个在它们之外计算的表达式,您只需要使用花括号,即;

<p ng-class="some-angular-variable">
  {{some-angular-variable}}
</p> 

In your situation, removing the double-curly braces and using double-quotes should solve the problem.

在您的情况下,删除双花括号并使用双引号应该可以解决问题。

As an aside, Chandermani is on the money - what you are trying to is better accomplished with the ng-class directive. Using it will allow to apply a class (or several) to the corresponding tag.

顺便说一句,Chandermani 很赚钱 - 您正在尝试使用 ng-class 指令更好地完成。使用它将允许将一个(或多个)类应用于相应的标签。

ie;

IE;

<p ng-class="mystyle">
    some text
</p>

say you have two classes style1 and style2

假设你有两个类 style1 和 style2

You can select whichever one to apply with

您可以选择任何一个申请

scope.mystyle = "style1" // or whatever

in your controller.

在您的控制器中。

回答by Denis

I can't understand why u want use thid idea! U should use ng-class for that!

我不明白你为什么要使用这个想法!你应该为此使用 ng-class!

For example:

例如:

<p ng-class="{strike: strike, bold: bold, red: red}">Map Senter code hereyntax Example</p>