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.
})
Root Scope All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.
The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.
$rootscope is available globally (for all Controllers), whereas $scope is available only to the Controller that has created it.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With