gpt4 book ai didi

angularjs - 为什么 AngularJS 指令编译不支持嵌套指令

转载 作者:行者123 更新时间:2023-12-04 08:45:22 26 4
gpt4 key购买 nike

在我的理解中,$compile 应该能够支持嵌套指令编译/链接,但是我们遇到了编译/链接不完整的问题——只有最外层的指令被渲染到 DOM 中,并且只有当两者都存在时才会重现该问题以下条件为真:

  1. 内部指令模板通过 templateUrl 加载(例如异步方式)
  2. 编译是在 Angular 上下文之外触发的。

我写了一个 jsfiddler 来演示它,下面列出了完整案例的部分代码 http://jsfiddle.net/pattern/7KjWP/

myApp.directive('plTest', function($compile){
return {
restrict :'A',
scope: {},
replace: true,
template: '<div>plTest rendered </div>',
link: function (scope, element){
$('#button1').on('click', function(){
var ele;
ele = $compile('<div pl-shared />')(scope);
console.log('plTest compile got : '+ ele[0].outerHTML);
// scope.$apply();
element.append(ele);
});
}
};
});

myApp.directive('plShared', function($compile, $timeout){
return {
restrict: 'A',
scope: {},
replace: true,
link: function (scope, element){
// comment out below line to make render success
//$timeout(function(){});
var el = $compile('<div pl-item></div>')(scope);
console.log('plShared compile got:' + el[0].outerHTML);
element.append(el);
}
};
});

myApp.directive('plItem', function($timeout){
return {
restrict: 'A',
scope:{},
template:'<div>plItem rendered <div pl-avatar/></div>',
link: function(scope){

}
};
});

myApp.directive('plAvatar', function(){
return {
restrict: 'A',
scope: {}
, templateUrl: 'avatar.html'
// ,template: 'content of avatar.html <div pl-image></div>'
};
});

有趣的是,我可以通过在调用 compile() 之后的某个地方调用 scope.$apply() 来解决这个问题(第 27 行)或将 $timeout(function(){}) 调用添加到内部指令之一的链接函数中(第 41 行)。这是缺陷还是设计使然?

最佳答案

$(foo).on(bar, handler) 是一个 jQuery 事件,这意味着 AngularJS 不知道它的细节,并且不会(不能)运行 apply-digest cycle在它之后处理所有绑定(bind)。

scope.$apply 就是为此而设计的,正如您所说的那样,修复了它。经验法则是:如果您使用其他库(特别是:在应用摘要循环之外)在 AngularJS 应用程序中实现 UI 功能,您必须自己调用 scope.$apply

喂!

关于angularjs - 为什么 AngularJS 指令编译不支持嵌套指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18396180/

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