Jenny Mok Jenny Mok - 16 days ago 12
AngularJS Question

Setter and getter using angular service/factory

I want to pass big chunk of data from controller A to controller B.

so I made this factory

angular.module('MyApp')
.factory('holdCustomCover', function($scope, img_data) {
return {
save: $scope.img_data = img_data;

get: $scope.img_data;
}
})


am I doing it right? so later in controller A what should I do? like
holdCustomCover.save(myImgDataHere)
?

Then in controller B I do
holdCustomCover.get()
I can get the img value?

Answer

You can't inject $scope inside factory/service funciton. Service/Factory are singleton object which are responsible for data sharing. You should have common code over there only.

In your code you have to create a function for getter & setter, which will return img_data which is private data for holdCustomer factory.

angular.module('MyApp')
  .factory('holdCustomCover', function() {
      var img_data; //private data
        return {
            //setter
            save: function (data){
              img_data = data;
            },
            //getter
            get: function(){
              return img_data;
            }
        }
 })
Comments