如果在单个DOM元素上具有多个指令,并且它们的应用顺序很重要,则可以使用该
priority属性对应用程序进行排序。较高的数字优先。如果未指定,则默认优先级为0。
编辑 :讨论之后,这是完整的工作解决方案。关键是 删除属性 :
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); } }; } }; });要么:
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); } }; });解释为什么我们必须设置terminal: true
and priority: 1000
(一个大数字):
当DOM准备就绪时,angular遍历DOM以标识所有已注册的指令,并根据
priority这些指令是否在同一元素
上来逐一编译指令。我们设定的自定义指令的优先级为较高的数字,以确保它会被编译 首先 ,用
terminal: true,其他指令将被 跳过
该指令被编译后。
编译我们的自定义指令时,它将通过添加指令并删除自身来修改元素,并使用$ compile服务 编译所有指令(包括已跳过的指令) 。
如果我们没有设置
terminal:trueand
priority: 1000,则有可能 在 自定义指令 之前先
编译一些指令。当我们的自定义指令使用$ compile编译element
=>时,再次编译已经编译的指令。这将导致无法预测的行为,尤其是如果在我们的自定义指令之前编译的指令已经转换了DOM。
也修改模板的指令的示例是
ng-repeat(priority = 1000),在
ng-repeat编译时,
ng-repeat
在应用其他指令之前先制作模板元素的副本 。



