我对这个功能有一些疑问。
假设我有这个指令:
.directive('hello', function () {
return {
template: '<div>Hello <span ng-transclude></span></div>',
restrict: 'E',
transclude: true,
compile: function() {
console.log('Compile()');
return {
pre: function() {
console.log('PreLink()');
},
post: function() {
console.log('PostLink()');
}
};
},
link: function postLink(scope, element, attrs) {
console.log('Link()');
}
};
}
我将它添加到我的模板中:
<hello>World</hello>
控制台日志:
Compile()
PreLink()
PostLink()
那么为什么是
link()
不被叫?如果不是从
compile()
返回一个对象我返回单个函数打印 PreLink()
控制台日志:Compile()
PreLink()
如果我没有从
Compile()
返回任何东西控制台日志:Compile()
尚
link()
没有被调用。如果我只是评论
Compile()
然后 Link()
最后打印:Link()
有人可以解释这一切吗?是
Link()
和 Compile()
一起工作的意思吗?我应该只使用 Compile 的 PreLink()
和 PostLink()
?
最佳答案
link
和 compile
不一起工作,不。
在指令定义对象中,如果你只有定义 link
,这就像有一个空 compile
的简写函数为空 preLink
使用您在 postLink
中的代码运行功能。只要您定义 compile
, link
被 angular 忽略,因为 compile 应该返回链接函数。
如果你只从 compile
返回一个函数,然后它会被执行 发帖 关联。
或者,换句话说,link
只是 postLink
的快捷方式在作用域被 compile
链接后调用的函数.
它(有点)记录在案 here - 查看代码示例中的注释。
关于AngularJS 指令 : Are Link and Compile functions meant to work together?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19797419/