How to pass an object using $ rootScope?

I have one function called saveInDB. What saves data in a database. The 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 another controller, where I need to access iObj to other controllers. I do not receive the object. In controllers I have

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

1) If your controllers are parent and you select an event from a child controller , you just need to fix this event, and the parent controller simply uses $ on to listen to it.

Emitting an event from a child controller:

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

Listening to an event (in the parent controller):

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

2) If your controllers are siblings

From your controller, you have an $emit event in the parent scope.

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

Then your parent area listens for this event and $broadcast it to its children. This method can be written inside an angular module .run block

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

Or you can enter $ rootScope into the controller and pass the $ broadcast event to it:

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

Areas interested in the event can subscribe to it:

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

You will need to do

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

and where do you want to catch

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

Source: https://habr.com/ru/post/1261909/


All Articles