如果您在单个 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);
          }
        };
      }
    };
  });
工作 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);
      }
    };
  });
演示
解释为什么我们必须设置terminal: true和priority: 1000(一个很大的数字):
当 DOM 准备好时,angular 会遍历 DOM 以识别所有已注册的指令,并根据priority 这些指令是否在同一元素上一一编译指令。我们设定的自定义指令的优先级为较高的数字,以确保它会被编译首先,用terminal: true,其他指令将被跳过该指令被编译后。
当我们的自定义指令被编译时,它将通过添加指令和删除自身来修改元素,并使用 $compile 服务来编译所有指令(包括那些被跳过的指令)。
如果我们不设置terminal:trueand priority: 1000,则有可能在我们的自定义指令之前编译某些指令。当我们的自定义指令使用 $compile 编译元素时 => 再次编译已经编译的指令。这将导致不可预测的行为,特别是如果在我们的自定义指令之前编译的指令已经转换了 DOM。
有关优先级和终端的更多信息,请查看如何理解指令的“终端”?
也修改模板的指令的示例是ng-repeat(priority = 1000),ng-repeat编译时,ng-repeat 在应用其他指令之前制作模板元素的副本。
感谢@Izhaki 的评论,这里是对ngRepeat源代码的引用:https : //github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js