Angular 指令 link 函数从不运行
Angular directive link function never runs
我遵循了 ng-bbok 的教程,在指令定义处插入了一个空的 compile
函数,然后是 link
函数。这样,link
函数中的代码就不会被执行。最后我发现这是因为空的 compile
函数,当我神奇地删除它时 link
被执行了。为什么会这样?我正在使用 Angular 1.3
{
compile: function() {},
link: function($scope, element, attributes) {
var size = attributes.gravatarSize || 80;
var hash = md5.digest_s($scope.email.from[0]);
$scope.gravatarImage = url + hash + '?size=' + size;
}
}
您不能同时定义 compile
属性 和 link
。如果您想使用 compile
函数,您可以 return 或 link 函数:
compile: function() {
return function($scope, element, attributes) {
var size = attributes.gravatarSize || 80;
var hash = md5.digest_s($scope.email.from[0]);
$scope.gravatarImage = url + hash + '?size=' + size;
}
}
或者同时定义pre
和post
(link)函数:
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
}
这是设计使然。引用 $compile docs:
link
This property is used only if the compile property is not defined.
我遵循了 ng-bbok 的教程,在指令定义处插入了一个空的 compile
函数,然后是 link
函数。这样,link
函数中的代码就不会被执行。最后我发现这是因为空的 compile
函数,当我神奇地删除它时 link
被执行了。为什么会这样?我正在使用 Angular 1.3
{
compile: function() {},
link: function($scope, element, attributes) {
var size = attributes.gravatarSize || 80;
var hash = md5.digest_s($scope.email.from[0]);
$scope.gravatarImage = url + hash + '?size=' + size;
}
}
您不能同时定义 compile
属性 和 link
。如果您想使用 compile
函数,您可以 return 或 link 函数:
compile: function() {
return function($scope, element, attributes) {
var size = attributes.gravatarSize || 80;
var hash = md5.digest_s($scope.email.from[0]);
$scope.gravatarImage = url + hash + '?size=' + size;
}
}
或者同时定义pre
和post
(link)函数:
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
}
这是设计使然。引用 $compile docs:
link
This property is used only if the compile property is not defined.