2015-04-07 51 views
0

说我有一个指令“foo”的编译模板:

app.directive("foo", function($compile) { 
    var innerTemplate = $compile('<div class="foo"></div>'); 
    return { 
     restrict: "E"; 
    }; 
})); 

为什么认为$编译调用将失败,抱怨fooDirective依赖于fooDirective,即使该指令被声明为仅限于“E”?

编辑:新增例如小提琴:https://jsfiddle.net/n4bvkbp7/1/

回答

1

该指令“富”必须完全定义,然后才能对其进行编译。尝试把你的编译语句进行指令链接功能:

app.directive("foo", function($compile) { 
    return { 
     restrict: "E", 
     link: function() { 
       var linkFn = $compile('<div class="foo"></div>'); 
     } 
    }; 
})); 
+0

它的工作原理给出语法'函数(){}'修正 –

+0

我假设你的意思'链接:函数(){//}' 。我试过了,它仍然会抛出同样的错误。 – markwongsk

0

我不明白为什么你需要一个$编译服务在这里:

ngModule.directive('foo', ['$compile', function($compile) { 
     return { 
      restrict: 'E', 
      template: '<div class="foo">foo</div>', 
      link: function(scope, element, attrs){ 

       //TODO: 
      } 

     } 

}]); 
+0

同意,它应该需要手动调用'$ compile',没有什么特别的模板。应该能够删除作为依赖也 – charlietfl

+0

我知道我可以使用'模板',如果我只想连接模板一次。但是,假设(为了假设的原因,如果仅仅是为了存在这种用例)我想将我的模板与两个不同的作用域链接起来,第二个作用域可能基于传入的作用域,例如: 'link :function(scope,element,attrs){element_append(template(scope)); } template.append(template(scope。$ new()); //可能是当前范围的克隆范围改变了一定的值 } – markwongsk

+0

@markwongsk这并没有太大的意义,如果这就是你所需要的,那么就是隔离范围 – charlietfl

0

您使用return语句之外$compile功能,即意味着它将在编译时执行,你只能编译你的元素postLink函数。

指令

var app = angular.module("app", []); 
app.directive("foo", function($compile) { 

    return { 
     restrict: "E", 
     link: function(scope, element, attrs){ 
      var innerTemplate = $compile('<div class="foo">HELLO WORLD</div>'); 
      element.append(innerTemplate(scope)); 
      //do other logic here 
     } 
    }; 
}); 

JsFiddle