Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS: How to call child scope function in parent scope

How can call a method defined in child scope from its parent scope?

function ParentCntl() {     // I want to call the $scope.get here }  function ChildCntl($scope) {     $scope.get = function() {         return "LOL";         } } 

http://jsfiddle.net/wUPdW/

like image 267
9blue Avatar asked Sep 26 '13 21:09

9blue


People also ask

How to call child method from parent in AngularJS?

child= {}; $scope. get = function(){ return $scope. child. get(); // you can call it.

How do you access child controller scope in parent controller?

In a nutshell: You cannot access child scopes from a parent scope. Your solutions: Define properties in parents and access them from children (read the link above) Use a service to share state.

How does a parent $scope relate to a child scope?

Angular scopes include a variable called $parent (i.e. $scope. $parent ) that refer to the parent scope of a controller. If a controller is at the root of the application, the parent would be the root scope ( $rootScope ). Child controllers can therefore modify the parent scope since they access to it.

Does AngularJS support scope inheritance?

The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes.


1 Answers

You can use $broadcast from the parent to a child:

function ParentCntl($scope) {      $scope.msg = "";     $scope.get = function(){         $scope.$broadcast ('someEvent');         return  $scope.msg;             } }  function ChildCntl($scope) {                    $scope.$on('someEvent', function(e) {           $scope.$parent.msg = $scope.get();                 });      $scope.get = function(){         return "LOL";         } } 

Working fiddle: http://jsfiddle.net/wUPdW/2/

UPDATE: There is another version, less coupled and more testable:

function ParentCntl($scope) {     $scope.msg = "";     $scope.get = function(){         $scope.$broadcast ('someEvent');         return  $scope.msg;             }      $scope.$on('pingBack', function(e,data) {           $scope.msg = data;             }); }  function ChildCntl($scope) {                    $scope.$on('someEvent', function(e) {           $scope.$emit("pingBack", $scope.get());             });      $scope.get = function(){         return "LOL";         } } 

Fiddle: http://jsfiddle.net/uypo360u/

like image 92
Ivan Chernykh Avatar answered Sep 19 '22 16:09

Ivan Chernykh