How to pass an object using $rootScope?

18,125

Solution 1

1) If your controllers are parent-child, and you're emitting the event from the child controller, you just need to $emit the event and the parent controller just uses $on to listen to it.

Emitting event from child controller:

$scope.SaveDB(iObj,function(iResult){
  $scope.$emit('saveCallback',iResult); //pass the data as the second parameter
});

Listening to the event (in parent controller):

$scope.$on('saveCallback',function(event,iResult){//receive the data as second parameter

});

2) If your controllers are siblings

From your controller, you $emit the event to the parent's scope.

$scope.SaveDB(iObj,function(iResult){

   $scope.$emit('saveCallback',iResult);
});

Your parent's scope then listens to this event and $broadcast it to its children. This method could be written inside angular module's .run block

$scope.$on('saveCallback',function (event,iresult){
    $scope.$broadcast('saveCallback',iresult);
});

Or you can inject the $rootScope to the controller and have it $broadcast the event:

$scope.SaveDB(iObj,function(iResult){
   $rootScope.$broadcast('saveCallback',iResult);
});

The scopes interested in the event can subscribe to it:

$scope.$on('saveCallBack',function(event, data) {
   //access data here 
});

Solution 2

You would have to do

$rootScope.$broadcast('saveCallback',iresult);

and where you want to catch

$scope.$on('saveCallBack',function(event, data) {
   //access data here 
});
Share:
18,125
Shardul Pendse
Author by

Shardul Pendse

Updated on June 12, 2022

Comments

  • Shardul Pendse
    Shardul Pendse almost 2 years

    I have one function named as saveInDB. Which saves data in the Database. Object is passed as a parameter to the function.

    $scope.SaveDB(iObj,function(iResult){
    //after a sucessfull opreation in the DB. Now  I need iObj to be passed to other controller.
    // I have used $emit method
    $rootScope.$emit('saveCallback');
    })
    

    In other controller where I need to access the iObj to other controllers. I am not getting the object. In a controllers I have

    var _save = $rootScope.$on('saveCallback',function(){
    //i want same obj(which is used for saving ) to be access here.
    })