【问题标题】:Access to the scope from a directive template's function从指令模板的函数访问范围
【发布时间】:2015-11-25 16:55:59
【问题描述】:

我正在尝试自动生成一些样式内容(在加载页面时以及在不同的 API 调用之后),所以我在我的视图中创建了一个在 <head> 标记中使用的指令。该指令使用函数自动生成模板,但是我需要能够使用一些简单的条件来添加或不添加一些东西到我的样式中(如果值不为空)。如果没有这个条件需要,我可以在不使用 $compile 而只使用“return { template: generate_dynamic_style ...}”的情况下使其正常工作。但我无法评估此 generate_dynamic_style 中的范围变量值。

我尝试通过编译将范围变量传递给它。所以这是我的代码:

    app.directive("dynamicstyle", function($compile) {
        var generate_dynamic_style = function(scope) {
            console.log('why scope works and I can see design Object inside :');
            console.log(scope);
            console.log('but scope.design doesnt work !!???');
            console.log(scope.design);
            var html_result = '<style type="text/css">'; // start style
            if (scope.design.layout_bg_image !== null) {
                html_result += 'html { color: {{design.layout_text_color}}; font-size: 12pt; text-align: {{design.layout_text_alignment}}; background: {{design.layout_bg_color}} url({{design.layout_bg_image}}) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } ';
            }
            html_result += 'body { color: {{design.layout_text_color}}; font-size: 12pt; text-align: {{design.layout_text_alignment}}; } ';
            html_result += '</style>'; // end style
            return html_result;
        };
        return {
            restrict: 'E',
            replace: true,
            link: function(scope, element, attrs) {
                // this log works
                console.log(scope);
                // this log doesn't work neither
                console.log(scope.design);
                var el = $compile(generate_dynamic_style(scope))(scope);
                element.replaceWith(el);
            }
        };
    });

你知道为什么我可以访问范围(当我检查元素时在 Firefox JS 控制台中)并开发里面的内容,我可以正确地看到设计对象以及其中的一些其他键值对。但是对于第二个 console.log(scope.design) 我得到一个奇怪的“未定义”? 当我之后尝试(如您在我的示例中看到的)链接中的相同内容时,我遇到了同样的问题。 我是否使用错误的语法来访问范围的内容?

我真的很困惑,浪费时间,因为我根本不明白问题出在哪里。

我愿意接受其他替代方案来满足我的需求:能够在我的模板中使用范围变量的空值周围的条件。

编辑:这是我制作的一个 plunker:Plunker example。不幸的是,我无法让我的问题再次发生,因为如果我将所有东西都放在同一个控制器中,一切显然都可以正常工作。实际上,就我而言,我使用路线。至少这个 plunker 示例允许我们确认我的代码正常工作,我没有语法错误......

非常感谢您为我提供的任何类型的帮助。

【问题讨论】:

  • 你有 plunkr 的例子吗? scope.design 也在链接函数中记录到控制台,这可能会造成混淆。
  • 谢谢我刚刚创建了一个 plunker 示例,您可以在我编辑的问题中找到它。我还更改了一些代码,以解释为什么我尝试从两个地方登录到控制台。顺便说一句,它适用于 plunker。

标签: javascript angularjs templates angularjs-directive scope


【解决方案1】:

我希望我能正确理解你。它似乎对我有用,我收到了未定义的消息并将指令放入主控制器中。如果我理解正确,那么这似乎可以按您的预期工作,see my plunkr

<body ng-controller="MainCtrl">
   <dynamicstyle></dynamicstyle>
   <p>Hello {{name}}!</p>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多