Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Access to child scope

Tags:

angularjs

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?

like image 853
Aziz Alfoudari Avatar asked Nov 17 '12 05:11

Aziz Alfoudari


1 Answers

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:

  1. Define properties in parents and access them from children (read the link above)
  2. Use a service to share state
  3. 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.
like image 75
jaime Avatar answered Dec 05 '22 11:12

jaime