In most angular applications, we use multiple controllers. Many cases arise when we to share data from one controller to another. Lets see how to handle these conditions.
Data Sharing With Service
Services are singleton instances which are shared among controllers. So to share data between controllers services are best option. Let’s make a very simple service to share data between controllers
mainMod.factory('dataShare',function($rootScope){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
};
return service;
});
In the above service, we have a function to “sendData”. This function store’s data in its object and then broadcasts an event ‘data_shared’. There is another function “getData” which simply return the data set in the service.
To use it in controllers, see the codepen below
Data Share between Controller with UI Router
If your application is using ‘$route’ or UI router, the controller to which you want to send data might not always be in memory. Let take an example of a application with a login page and a dashboard page. After user gets logged in, the dashboard page opens. So on login, you need to pass data from login controller to dashboard controller. Using the above logic a pseudo code would be
//login controller
$scope.login = function(){
var ajax = $http.post('127.0.0.1/login:5000′,{user:'test',pass:'test'});
ajax.then(function(data){
//login success
dataShare.sendData(data);
$location.path('/dashboard');
});
};
//dashboard controller
$scope.$on('data_shared',function(){
var data = dataShare.getData();
});
The above is same logic which we used previously, only this time this won’t work. The reason being, ‘dashboard controller’ is not in memory when the dataShare event was fired. It came into memory after the dashboard page was opened, but by this time ‘$rootScope.$broadcast’ has already taken place and the dashboard controller missed the event.
To fix this issue we need to make a small change in our dataShare service
mainMod.factory('dataShare',function($rootScope,$timeout){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$timeout(function(){
$rootScope.$broadcast('data_shared');
},100);
};
service.getData = function(){
return this.data;
};
return service;
});
I have just added a timeout of 100 milisec before firing the data_shared event. Because of this, the dashboard controller comes into memory and receives the event.