如果您在单个 DOM 元素上有多个指令并且
它们的应用顺序,您可以使用priority 属性对其进行排序
应用。较大的数字首先运行。如果您不指定优先级,则默认优先级为 0。
编辑:经过讨论,这是完整的工作解决方案。关键是删除属性:element.removeAttr("common-things");,还有element.removeAttr("data-common-things");(如果用户在html中指定data-common-things)
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);
}
};
}
};
});
工作插件可在:http://plnkr.co/edit/Q13bUt?p=preview
或者:
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
解释为什么我们必须设置terminal: true 和priority: 1000(一个很大的数字):
当 DOM 准备好后,Angular 会遍历 DOM 以识别所有已注册的指令,并根据 priority如果这些指令在同一个元素上,将这些指令一一编译。我们将自定义指令的优先级设置为较高的数字,以确保它会被首先编译,而使用terminal: true,其他指令将在编译该指令后跳过。
当我们的自定义指令被编译时,它会通过添加指令和删除自身来修改元素,并使用 $compile 服务来编译所有指令(包括那些被跳过的指令)。
如果我们不设置terminal:true 和priority: 1000,则有可能某些指令在我们的自定义指令之前编译。当我们的自定义指令使用 $compile 编译元素时 => 再次编译已经编译的指令。这将导致不可预知的行为,特别是如果在我们的自定义指令之前编译的指令已经转换了 DOM。
有关优先级和终端的更多信息,请查看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