How to pass an object using $rootScope?

丶灬走出姿态 提交于 2019-12-21 17:01:55

问题


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.
})

回答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 
});



回答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 
});


来源:https://stackoverflow.com/questions/21346565/how-to-pass-an-object-using-rootscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!