Services are always the best way to store data between controllers. The service saves data through the application life cycle, so we can create a simple way:
DataCacheService
angular.module('dataPassingDemo').service('DataCacheService', DataCacheService);
function DataCacheService () {
var self = this,
_cache = {};
self.get = get;
self.set = set;
function get (key) {
if (angular.isDefined(key) && angular.isDefined(_cache[key])) {
return _cache[key];
}
return false;
}
function set (key, value) {
if (angular.isDefined(key)) {
_cache[key] = value;
}
}
Then, given the two controllers:
Controller 1
angular.module('dataPassingDemo').controller('Controller1', Controller1);
function Controller1 (DataCacheService) {
var vm = this;
vm.setName = setName;
function setName (name) {
DataCacheService.set('name', name);
}
}
Controller 2
angular.module('dataPassingDemo').controller('Controller2', Controller2);
function Controller2 (DataCacheService) {
var vm = this;
vm.name = DataCacheService.get('name');
}
You can see that we can easily transfer data between two controllers.
You can get more information about services and factories from in this article .
source
share