请有人能解释一下,为什么 attrDir
的范围变量可见,而 oneWay
不可见?
我认为 scope:{}
也是孤立的。
angular.module('test', []);
angular.module('test').directive('attrDir', attrDir);
function attrDir(){
return {
scope: true,
link: function(scope){
scope.hello = 'attrDir';
}
};
}
angular.module('test').directive('oneWay', oneWay);
function oneWay(){
return {
scope: {
data: '<?'
},
link: function(scope){
scope.hello = 'oneWay';
}
};
}
hello
只会在 attr-dir
中呈现。
<attr-dir>
<span>{{hello}}</span>
</attr-dir>
<one-way>
<span>{{hello}}</span>
</one-way>
这是一个笨蛋:https://plnkr.co/edit/2CM4vVRshWuJvaBj2q8T?p=preview
谢谢。
最佳答案
首先,您观察到的与<
无关。绑定(bind)。
问题是表达式 {{hello}}
在这两个指令中,不是这些指令模板的一部分。对于这些元素,绑定(bind)规则是不同的。
Angular 自动为 {{hello}}
创建链接函数表达式。但是在您的情况下,评估这些链接功能的范围是不同的。
您可能期望的是:
rootScope
/ \
/ \
attr-dir-new-scope one-way-isoloate-scope
/ \
/ \
{{hello}} {{hello}}
然而,根据this comment in source :
// We only pass the isolate scope, if the isolate directive has a template,
// otherwise the child elements do not belong to the isolate directive.
真实的画面是这样的:
root scope
/ \ \
/ \ \
attr-dir-new-scope \ one-way-isoloate-scope
/ \
/ \
{{hello}} {{hello}}
因此在您的示例中,第一个指令 <attr-dir>
不创建隔离范围,而是创建新范围,因此当链接 Angular 将这个新范围传递给指令的链接功能时:
link: function(scope){
scope.hello = 'attrDir';
}
以及为 {{hello}}
创建的链接函数表达。这就是为什么当您在链接函数中添加一个值时,它在表达式链接函数中可用。
但是你的第二个指令<one-way>
创建 isolate scope 并且根据我上面提到的评论,指令的链接函数得到 isolate scope 它应该的,但是表达式的链接函数收到 不同的范围(您的示例中的根范围)。所以你要添加 hello
不同范围的值(value)。这就是该值未定义的原因。
关于AngularJS:指令隔离范围 - 范围变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728977/