0

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 Answers 2

2

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;
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

To receive data you need to :

$rootScope.$on('data_shared', function(evt, data) {
});

It is async operation, so you cannot invoke it synchronously. If you want to abstract the communication, you need to implement you own observer/subscriber pattern.

1 Comment

this issue is when the console.log in my .factory returns an empty {}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.