【问题标题】:Directive's link is not rendering variable in the scope指令的链接不在范围内呈现变量
【发布时间】:2015-02-25 16:55:35
【问题描述】:

我希望该指令能够打印带有 {{ }} 内的值的模板已解析,但事实并非如此。它打印出{{argVal}},就好像它是一段 HTML 字符串。

myApp.directive('myArgs', [function() {

    var theTemplate = 
        '<span>{</span>' + 
            '<div ng-if="typeIsArray(argVal)">'+
                '<p>{{argVal}}</p>'
                '<my-args arg-val="argVal[0]"></my-args>'
            '</div>';

    return {
        restrict: "E",
        scope: {
            argVal: '='
        },
        controller: ... //contains utils to check type of argVal
        link: function(scope, element){
            alert(scope.argVal);
            element.html('').append(theTemplate);
        }
      };        
}]);

在我的 HTML 文件中,我只是像这样调用指令:

<my-args arg-val="someArray"></my-args> 

someArray在控制器中定义为$scope.someArray = ["ola", "hi", "bonjour"];

someArray 肯定在范围内,因为 alert(someArray) 正在工作。

那么为什么模板部分不能正确渲染呢?

【问题讨论】:

    标签: angularjs angularjs-scope angular-directive


    【解决方案1】:

    你需要编译带有作用域的模板

    element.html('').append(theTemplate);
    $compile(element.contents())(scope);
    

    别忘了提供依赖 $compile 到指令。

    【讨论】:

    • 如果您使用的是动态模板,那么 Angular 不会使用指令渲染它并且不知道范围,因此您必须使用一些范围编译它并以角度方式渲染它。但它是您直接提供的this to template:'
      {{xyz}}
      ' 它被认为是静态模板并在编译模板本身时以指令范围呈现。
    【解决方案2】:

    您不应该直接将模板附加到元素。像这样使用指令的模板属性:

        myApp.directive('myArgs', [function() {
    
        var theTemplate = 
            '<span>{</span>' + 
                '<div ng-if="typeIsArray(argVal)">'+
                    '<p>{{argVal}}</p>'
                    '<my-args arg-val="argVal[0]"></my-args>'
                '</div>';
    
        return {
            restrict: "E",
            scope: {
                argVal: '='
            },
            controller: ... //contains utils to check type of argVal
            template: theTemplate,  // this will eval correctly
            link: function(scope, element){
                alert(scope.argVal);
    
                // this is not needed
                //element.html('').append(theTemplate);
            }
          };        
    }]);
    

    【讨论】:

    • 这是因为你使用的是动态模板,现在它是静态的,由指令本身编译。如果你需要动态模板,你需要通过 $compile 手动编译它。
    • 等等,现在是静态的还是动态的?我以为是动态的。我需要$compile 还是我可以使用你的方式?
    • 您应该尽可能使用模板属性。如果您动态生成模板,请仅在链接 fn 中使用 $compile。
    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多