简体   繁体   中英

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 BI do holdCustomCover.get() I can get the img value?

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;
            }
        }
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM