0

I am creating a mid-sized angular app and have a need to store data and use it at the end of the user journey to send off to the server (company security policy is one transport of customer data - unless 100% unavoidable - dont ask!)

so I've been doing a little bit of reading as still quite new to angular and think I've decided the best and cleanest way to do this is to have a "dataFactory" or service so as not to pollute the app with a "master controller" etc, etc

my question is, within this service, do I just have a normal variable which I can assign key:values to or is it better to create a cacheFactory within the service to store the data?

what are the pros/cons of each?

DrogoNevets
  • 1,456
  • 3
  • 18
  • 34

1 Answers1

1

You need to create a service to store data.

Globals are ever a bad practice - and this is the same for a normal object lost somewhere in your code.

Solution below:

// service
myApp.service('controllerSharingData', function() {
  var __variables = {};

  return {
   get: function(varname) {
    return (typeof __variables[varname] !== 'undefined') ? __variables[varname] : false;
   },
   set: function(varname, value) {
    __variables[varname] = value;
   }
  };
});

// controllers
myApp.controller('IndexCtrl', function($scope, controllerSharingData) {
  controllerSharingData.set('toto', 'hello world');
});

myApp.controller('ListCtrl', function($scope, controllerSharingData) {
  alert(controllerSharingData.get('toto'));
});
Community
  • 1
  • 1
Paul Rad
  • 4,820
  • 1
  • 22
  • 23