I seem to be facing a problem with sharing data between controllers in angularjs I have two HTML files, one controller for each of them, a service to share Information and a regular app file for routing.
Here's the first file
<div class="container">
<button ng-click="broadcastData()"> Send </button> </div>
Here's the corresponding Controller for it:
angular.module('myApp').controller('sendInfoController',
['$scope','$rootScope','$location'
function ($scope,$rootScope, $location)
{
$scope.broadcastData=function()
{
shareInfoService.sendData({info: "Okay"});
$location.path('/infoView');
}
}]);
Here's the second HTML File: (infoView.html)
<div>
{{data}}
</div>
Here's the corresponding controller for it:
angular.module('myApp').controller('infoController',
['$scope','$rootScope',
function ($scope,$rootScope)
{
$scope.data="hello";
$rootScope.$on('sendTheData', function(event,args)
{
console.log(args);
$scope.data=args.info;
});
console.log($scope.data);
}]);
Here's the service to share information:
angular.module('prkApp').factory('shareInfoService',
['$rootScope',
function ($rootScope) {
//Return the particular function
return ({
sendData: sendData
});
function sendData(data)
{
$rootScope.$broadcast('sendTheData', data);
};
}]);
When I click on the button in the first HTML File, the location gets changed to infoView and the shareInfoService.broadcastData function gets called.
It redirects to the second HTML File. However, the information that is displayed on this page is "hello" and not "Okay".
The web console logs shows {info: "Okay"} first and "hello" immediately after that.
How can it be rectified so as to show the data that is sent by the previous controller?