多个directive定义在一个DOM元素上时的编译和链接顺序---执行顺序

js代码:

myapp.controller('ctrl',['$scope',function ($scope) {
    $scope.ability=[];
}]);

myapp.directive('supperman',function () {
    return {
        restrict:'AE',
        // scope:{},
        controller:function ($scope) {             // controller是一个函数
            // $scope.ability=[];                      // 内部controller需要$scope
           this.add1 = function () {
               $scope.ability.push("aaa");
           };
           this.add2 = function () {
               $scope.ability.push("bbb");
           };
           this.add3 = function () {
               $scope.ability.push("ccc");
           };

        },
        link:function (scope,element,attr) {
            element.bind('mouseenter',function () {
                console.log(scope.ability);     // 这里已经用scope接收了上级传过来的$scope了,当然要用形参名调用,不能再用$scope
            });
        }
    }
});

myapp.directive('add111',function () {
    return {
        // template:'
hello add1
',
require:'^supperman', // 这里引入的是directive!!!!,不是controller link:function (scope,element,attr,ctrl) { debugger ctrl.add1(); } } }); myapp.directive('add222',function () { return { // template:'
hello add2}
', // restrict默认是A
require:'^supperman', link:function (scope,element,attr,ctrl) { debugger ctrl.add2(); } } }); myapp.directive('add333',function () { return { // template:'
hello add3
',
require:'^supperman', link:function (scope,element,attr,ctrl) { debugger ctrl.add3(); } } });
 
  
 
  
html代码:
 
  
 
  
<div>
    <supperman add111>超人1supperman>
div>
<div>
    <supperman add111 add222 >超人2supperman>
div>
<div>
    <supperman add111 add222 add333>超人3supperman>
div>


执行结果:




原因解释:
见angular官方文档

When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.

当多个directive作用在一个dom元素上时,需要 priority来指定directive的执行顺序,priority用数字;
compile的时候优先级大的先编译;
link的时候优先级大的后链接,逆序。
优先级不指定默认是0,执行顺序是无法确定的。
 
  

你可能感兴趣的:(多个directive定义在一个DOM元素上时的编译和链接顺序---执行顺序)