未遵守指令的预链接排序

时间:2014-10-30 19:32:32

标签: angularjs angularjs-directive

我希望了解嵌套指令中prelink的顺序。我有以下html:

<directive-a ng-model="model1" directive-b="true">

</directive-a>

<ssn-widget ng-model="abc" hc-initial="true">

</ssn-widget>

关注相关的javascript:

angular.module("directiveTest", [])
.directive("directiveA", function(){
  return {
    require: "ngModel",
    restrict: "E",
    compile: function(){
      return {
        pre: function(scope, element, attrs, ngModelCtrl){
          alert("in pre of directiveA");
        }
      }

    }
  };
})
.directive("directiveB", function(){
  return {
    require : "ngModel",
    restrict: "A",
    compile: function(){
      return {
        pre: function(scope, element, attrs, ngModelCtrl){
          alert("in pre of directiveB");
        }
      }

    }
  };
})
.directive("ssnWidget", function(){
  return {
    require: "ngModel",
    restrict: "E",
    compile: function(){
      return {
        pre: function(scope, element, attrs, ngModelCtrl){
          alert("in pre of ssnWidget");
        }
      }

    }
  };
})
.directive("hcInitial", function(){
  return {
    require : "ngModel",
    restrict: "A",
    compile: function(){
      return {
        pre: function(scope, element, attrs, ngModelCtrl){
          alert("in pre of hcInitial");
        }
      }

    }
  };
});

我的印象是预链接功能从父级到子级运行。因此,directive-assn-widget的预链接功能应分别在directive-bhc-initial之前运行。但是,directive-adirective-b对都是如此,但ssn-widgethc-initial则不然。我无法理解这种行为。以下是吸虫:

Plunker

1 个答案:

答案 0 :(得分:1)

指令未嵌套在您的示例中,它们位于相同的级别/标记

嵌套指令是其他指令的子代:

<dir-a>
  <dir-b></dir-b>
</dir-a>

我不知道但是,对于同一级别的指令,角度按字母顺序编译它们。如果你将ssnWidget重命名为gsnWidget,它将在hcInitial之前编译

更改此行为的最佳方法是在DDO中使用优先级属性。

.directive("ssnWidget", function(){
  return {
    require: "ngModel",
    restrict: "E",
    priority: 2,
    compile: function(){
      return {
        pre: function(scope, element, attrs, ngModelCtrl){
          alert("in pre of ssnWidget");
        }
      }

    }
  };
})