如果您在单个 DOM 元素上有多个指令并且其中
它们的应用顺序很重要,您可以使用priority
财产来订购他们的
应用。数字较大的先运行。如果不指定优先级,则默认为 0。
EDIT:经过讨论,这是完整的工作解决方案。关键是删除属性: element.removeAttr("common-things");
,并且element.removeAttr("data-common-things");
(如果用户指定data-common-things
在 HTML 中)
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true, //this setting is important, see explanation below
priority: 1000, //this setting is important, see explanation below
compile: function compile(element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});
工作 plunker 可在以下位置找到:http://plnkr.co/edit/Q13bUt?p=preview http://plnkr.co/edit/Q13bUt?p=preview
Or:
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
$compile(element)(scope);
}
};
});
DEMO http://plnkr.co/edit/Tw1Pbt?p=preview
解释为什么我们必须设置terminal: true
and priority: 1000
(一个很高的数字):
当 DOM 准备好后,Angular 会遍历 DOM 来识别所有已注册的指令,并根据priority
如果这些指令位于同一元素上。我们将自定义指令的优先级设置为较高的数字,以确保它将被编译first与terminal: true
,其他指令将是skipped该指令编译后。
当我们的自定义指令被编译时,它将通过添加指令和删除自身来修改元素,并使用 $compile 服务来编译所有指令(包括那些被跳过的指令).
如果我们不设置terminal:true
and priority: 1000
,有可能编译某些指令before我们的自定义指令。当我们的自定义指令使用 $compile 编译元素时 => 再次编译已经编译的指令。这将导致不可预测的行为,特别是如果在我们的自定义指令之前编译的指令已经转换了 DOM。
有关优先级和终端的更多信息,请查看如何理解指令的“terminal”? https://stackoverflow.com/questions/15266840/how-to-understand-the-terminal-of-directive
也修改模板的指令的示例是ng-repeat
(优先级 = 1000),当ng-repeat
被编译,ng-repeat
在应用其他指令之前复制模板元素.
感谢@Izhaki 的评论,这里是对ngRepeat
源代码:https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js