指令与根元素与ngRepeat并替换:真 [英] Directive with root element with ngRepeat and replace: true
问题描述
有人能解释背后的以下行为的根本原因?
Can someone explain the root cause behind the following behavior?
如果与分离范围范围指令:{}
与 NG-重复
键,一个根元素替换:真正的
那么它休息的分离范围,这意味着分离范围无法访问/可见的指令中,并指令开始从外部范围接收变量
If a directive with isolate scope scope: {}
has a root element with ng-repeat
AND replace: true
then it "breaks" the isolate scope, meaning that the isolate scope is not accessible/visible from within the directive, and the directive starts receiving variables from the outer scope.
下面是微创重复的例子,我可以做:
Here's the minimally reproducible example I could make:
app.controller('MainCtrl', function($scope) {
$scope.name = 'MainCtrl';
});
app.directive("foo", function(){
return {
replace: true,
scope: {},
template: "<div ng-repeat='item in [1]'>{{name}}</div>",
controller: function($scope){
$scope.name = "foo";
}
};
});
下面的视图会令MainCtrl
The following view would render "MainCtrl":
<div ng-controller="MainCtrl">
<foo></foo>
</div>
添加任何非 - NG-重复
-able根模板或设置更换:假
渲染预期的结果为foo。
Adding either a non-ng-repeat
-able root to the template OR setting replace: false
renders the expected result "foo".
推荐答案
这并不只是发生了NG-重复,这似乎发生了创建像 A范围内的任何其他指令NG-如果
为好。它看起来像,这是因为该指令的隔离范围得到了NG-repeat的子范围覆盖。而由于替换:真正的
选项NG-重复成为指令源元素即一部分&LT;富&GT;&LT; / foo的&GT;
和NG-重复的子范围从最终母公司范围 MainCtrl
(这似乎是错误的)计算,这导致整个指令模板是绑定到控制器的任何插值的子范围有针对该范围进行评估。因此,你看到主控制器的范围,该指令正在扩大。这似乎是一个错误。
It does not just happen for ng-repeat, this seems to happen for any other directives that creates a scope like ng-if
as well. And it seems like, this is because the directive's isolated scope gets overwritten by the ng-repeat's child scope. And because of replace:true
option ng-repeat becomes a part of the directive source element i.e <foo></foo>
and the child scope of ng-repeat is calculated from the ultimate parent scope MainCtrl
(Which appears to be wrong) and this causes the entire directive template to be bound to the child scope of controller and any interpolations are evaluated against that scope. Hence you see main controller's scope being expanded in the directive. This seems like a bug.
这篇关于指令与根元素与ngRepeat并替换:真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!