noor h noor h - 4 months ago 25
AngularJS Question

sharing data between controllers, ionic + angular js

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 ?

Answer

Factory code is not written correctly and also you should use angular service instead of creating factory since you have to only share data between controllers. Although both are singleton objects.

Lets do it with factory first

.factory('dataShare',function(){
  var service = {
     sendData: sendData,
     getData: getData
  };

  var serviceData;

  function sendData(data){
      serviceData = data;
  }

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

  return service;
});

Lets do it with service

.service('dataShare',function(){
  var serviceData;

  this.sendData = function(data){
      serviceData = data;
  }

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