AngularJS - 访问子作用域 [英] AngularJS - Access to child scope
问题描述
如果我有以下控制器:
function parent($scope, service) {
$scope.a = 'foo';
$scope.save = function() {
service.save({
a: $scope.a,
b: $scope.b
});
}
}
function child($scope) {
$scope.b = 'bar';
}
让 parent
从 child
中读取 b
的正确方法是什么?如果有必要在 parent
中定义 b
,假设 b
是描述与 child
而不是 parent
?
What's the proper way to let parent
read b
out of child
? If it's necessary to define b
in parent
, wouldn't that make it semantically incorrect assuming that b
is a property that describes something related to child
and not parent
?
更新:进一步考虑一下,如果有多个孩子拥有b
,那么父
会在哪个上产生冲突b
检索.我的问题仍然存在,从 parent
访问 b
的正确方法是什么?
Update: Thinking further about it, if more than one child had b
it would create a conflict for parent
on which b
to retrieve. My question remains, what's the proper way to access b
from parent
?
推荐答案
AngularJS 中的作用域使用原型继承,当在子作用域中查找属性时,解释器将查找从子作用域开始并继续到父作用域的原型链直到它找到财产,而不是相反.
Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.
查看 Vojta 对该问题的评论 https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J
Check Vojta's comments on the issue https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J
简而言之:您不能从父作用域访问子作用域.
In a nutshell: You cannot access child scopes from a parent scope.
您的解决方案:
- 在父级中定义属性并从子级访问它们(阅读上面的链接)
- 使用服务共享状态
- 通过事件传递数据.
$emit
向上发送事件到父级,直到根作用域,$broadcast
向下发送事件.这可能有助于您在语义上保持正确.
- Define properties in parents and access them from children (read the link above)
- Use a service to share state
- Pass data through events.
$emit
sends events upwards to parents until the root scope and$broadcast
dispatches events downwards. This might help you to keep things semantically correct.
这篇关于AngularJS - 访问子作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!