gpt4 book ai didi

javascript - 为什么嵌套指令 Controller 和 Link 函数触发顺序取决于 template 和 templateUrl?

转载 作者:行者123 更新时间:2023-11-30 16:24:05 25 4
gpt4 key购买 nike

我正在使用 AngularJs 1.4.8,我注意到奇怪的行为:

当你有 2 个指令时:

angular.module('another-module', [])
.directive('anotherModuleOuter', function () {
return {
scope: {},
controller: function () {
console.log('another-module-outer - controller');
},
link: function () {
console.log('another-module-outer - link');
},
template: '<div>another-module-outer <div another-module-inner></div></div>'
}
})
.directive('anotherModuleInner', function () {
return {
scope: {},
controller: function () {
console.log('another-module-inner - controller');
},
link: function () {
console.log('another-module-inner - link');
},
template: '<div>another-module-inner</div>'
}
});

你会得到

another-module-outer - controller
another-module-inner - controller
another-module-inner - link
another-module-outer - link

这意味着外部指令的 Controller 将首先被调用,链接函数最后被调用。

但是,如果您更改 inner 的模板:

template: '<div>another-module-inner</div>'

像这样的 templateUrl:

templateUrl: 'anotherModuleInner.html'

加载顺序也会改变(外部指令的链接将在内部 Controller 之前触发):

another-module-outer - controller
another-module-outer - link
another-module-inner - controller
another-module-inner - link

为什么会这样?

附言/

我在处理内部指令注册 $scope.$on() 和外部触发 $rootScope.$broadcast() 的事件时遇到问题,但由于内部函数 $on 在广播后注册,因此它不会捕获任何内容。如果您提出解决方案,我将不胜感激。

最佳答案

您正在寻找的答案在 $compile for templateUrl 下的文档中

Because template loading is asynchronous the compiler will suspend compilation of directives on that element for later when the template has been resolved. In the meantime it will continue to compile and link sibling and parent elements as though this element had not contained any directives.

关于javascript - 为什么嵌套指令 Controller 和 Link 函数触发顺序取决于 template 和 templateUrl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34364862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com