如果在单个DOM元素上有多个指令,并且
它们被应用的顺序,您可以使用priority
属性来排序它们的
申请.数字越高,就会先运行.如果未指定优先级,则默认优先级为0.
EDIT:经过讨论,下面是完整的工作解决方案.关键是remove the attribute: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);
}
};
}
};
});
工作plunker的价格为: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个
Explanation why we have to set 100 and 101 (a high number):
当DOM准备就绪时,angular将遍历DOM以识别所有已注册的指令,并基于priority
if these directives are on the same element逐个编译这些指令.我们将自定义指令的优先级设置为一个较高的数字,以确保它将被编译为first,对于terminal: true
,其他指令将在编译该指令后被编译为skipped.
当我们的自定义指令被编译时,它将通过添加指令和删除自身来修改元素,并使用$compile service将其设置为compile all the directives (including those that were skipped).
If we don't set terminal:true
and priority: 1000
, there is a chance that some directives are compiled before our custom directive. And when our custom directive uses $compile to compile the element => compile again the already compiled directives. This will cause unpredictable behavior especially if the directives compiled before our custom directive have already transformed the DOM.
有关优先级和终端的更多信息,请查看How to understand the `terminal` of directive?
同样修改模板的指令示例为ng-repeat
(优先级=ng-repeat
0),编译ng-repeat
时为ng-repeat
make copies of the template element before other directives get applied.
感谢@Izhaki的 comments ,这里是ngRepeat
源代码的参考:https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js