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

本文探讨了在AngularJS中,当一个DOM元素上存在多个指令时,它们的编译和链接阶段的执行顺序。通过深入理解这一过程,开发者可以更好地控制和协调应用中的指令交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:'<div>hello add1 </div>',
        require:'^supperman',                       // 这里引入的是directive!!!!,不是controller
        link:function (scope,element,attr,ctrl) {
            debugger
            ctrl.add1();
        }
    }
});

myapp.directive('add222',function () {
    return {
        
        // template:'<div>hello add2}</div>',         // restrict默认是A
        require:'^supperman',
        link:function (scope,element,attr,ctrl) {
            debugger
            ctrl.add2();
        }
    }
});

myapp.directive('add333',function () {
    return {
        // template:'<div>hello add3 </div>',
        require:'^supperman',
        link:function (scope,element,attr,ctrl) {
            debugger
            ctrl.add3();
        }
    }
});
 
 
html代码:
 
<div>
    <supperman add111>超人1</supperman>
</div>
<div>
    <supperman add111 add222 >超人2</supperman>
</div>
<div>
    <supperman add111 add222 add333>超人3</supperman>
</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,执行顺序是无法确定的。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值