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';
}
什么是让父
读 B
出儿童$的正确方法C $ C>?如果有必要来定义
B
在父
,也不会使它语义上不正确假设乙
是介绍与孩子
,这也不是一个属性父
?
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
检索。我的问题是,什么是访问的正确方法 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使用原型继承,在子范围查找属性时间preTER将查找原型链从孩子开始,继续给父母,直到它找到的财产,而不是其他的方式。
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开发的评论href=\"https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J\">https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J
在一言以蔽之:你不能从父范围内访问子作用域。
In a nutshell: You cannot access child scopes from a parent scope.
您的解决方案:
- 在父母的定义特性和儿童访问它们(阅读上面的链接)
- 使用服务来共享状态
- 通过活动传递数据。
$发出
向上将事件发送给家长,直到根范围和$广播
向下调度事件。这可以帮助你使事情语义正确。
- 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屋!