If I have the following controllers:
function parent($scope, service) { $scope.a = 'foo'; $scope.save = function() { service.save({ a: $scope.a, b: $scope.b }); } } function child($scope) { $scope.b = 'bar'; }
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
?
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
?
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.
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.
Your solutions:
$emit
sends events upwards to parents until the root scope and $broadcast
dispatches events downwards. This might help you to keep things semantically correct.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With