How to share data between controllers?


#1

these are my controllers:

.controller('recommendedJobsCtrl', function($q,$scope, $ionicSideMenuDelegate,$window,$http,dataShare) {
    $scope.text='hey world';
    $scope.post=function(){
      dataShare.sendData($scope.text);
       console.log('sent: ' + $scope.text);
    }   
 })
.controller('jobsCtrl', function($scope,dataShare) {
   $scope.words=dataShare.getData();
})

and this is my factory:

.factory('dataShare',function($rootScope){
  var service = {};

    service.sendData = function(data){
      service=data;
      $rootScope.$broadcast('data_shared', service);
     },

    service.getData = function(){
      console.log('this.data is ' + service)
      return service;
     
    };
  return service;
});

when the console.log prints, service is empty. How do i fix this ?


#2

Hi there. I don’t know if this will help you, but here’s the factory I use in all my apps.

.factory('sharedParams', function () {
return {
    BearerToken: "",
    LoggedIn: false,
    LoggingIn: false,
    LastRequest: "",
    Username: "",
    Password: "",
    LoginError: false,
    SearchAgentString: "",
    SearchAgentResults:[]

}
}}

and in my controllers…

app.controller('AgentsController', function ($scope, sharedParams, $http, $ionicPopup, AgentsSvc) {
    $scope.$emit("ChangeSubheader", "");
    $scope.QueryTerms = "";
    sharedParams.SearchAgentString = SearchTerms;
})

Perhaps you can try this approach first and then try adding back in some of the items you’d like to use in your current implementation? I hope it helps a bit.


#3

thank you for your reply, how would i get the data ‘SearchAgentString’ from another controller?


#4

So let’s say your other controller is SettingsController for example, and you’d need that SearchAgentString that was set to the SearchTerms we just set in the AgentsController. You’d do something like this (untested code since it’s a little late at night here.)

app.controller('SettingsController', function ($scope, sharedParams, $http, $ionicPopup, SettingsSvc) {
    // Let's just display in the console log the sharedParams term we want from the AgentsController
    console.log("The SearchAgentString value is: " + sharedParams.SearchAgentString);
})

That should display the value from the other controller just fine. Let me know if I can be of any other help.