具有隔离和非隔离作用域的指令内部内容 [英] Directive inner content with isolated and non-isolated scopes
问题描述
我发现指令的内部内容 scope:true 类型的行为非常奇怪:
I found quite a strange behaviour of scope:true type for inner content of a directive:
<body ng-init="x=10">
<mydir>
{{x}}
</mydir>
</body>
所以 {{x}} 是内部内容,指令定义是:
so {{x}} is inner content, and directive definition is:
.directive('mydir', function() {
return {
scope: {},
link: function(scope){
scope.x = 5;
}
};
});
当我们将作用域定义为隔离 (scope:{}) 时,它输出 {{x}} 为 10,因此使用外部作用域.但是当我们为指令创建新的作用域 (scope:true) 时,它会将它用于内部内容和输出 5.因此它为 2 种情况使用不同的内部内容作用域.有人能给我一个提示/链接到源代码/手册来解释这种不一致吗?
When we define scope as isolated (scope:{}), it outputs {{x}} as 10, so uses outer scope. But when we create new scope for the directive(scope:true), it will use it for inner content and output 5. So it uses different scopes for inner content for 2 cases. Could somebody give me a hint/link to souce code/manual for the explanation for this inconsistency?
这是 plnk 来玩代码.
UPD:我了解什么是 JavaScript 原型继承.我知道指令范围类型之间的区别.我的目标不是显示 5 而不是 10.问题是关于内部模板,在这两种情况下都应该插入父作用域,父作用域无法访问子/隔离的属性.
UPD: I understand what is JavaScript prototype inheritance. I know the difference between directive scope types. And my aim is not to display 5 instead of 10. The question is about inner template that in both cases should be interpolated with parent scope, which does not have access to properties of child/isolated one.
推荐答案
A 从 angular 问题中得到了答案:https://github.com/angular/angular.js/issues/13845#issuecomment-174953398
A got the answer from angular issues: https://github.com/angular/angular.js/issues/13845#issuecomment-174953398
var scopeToChild = scope;
if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
scopeToChild = isolateScope;
}
childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
简历:对于隔离的作用域类型,作用域仅提供给指令模板,而不提供给内部内容.
resume: In case of isolated scope type, scope is provided ONLY for directive template, but not for inner content.
这篇关于具有隔离和非隔离作用域的指令内部内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!