Skip to content

Instantly share code, notes, and snippets.

@jtrussell
Last active December 17, 2015 17:29
Show Gist options
  • Save jtrussell/5646086 to your computer and use it in GitHub Desktop.
Save jtrussell/5646086 to your computer and use it in GitHub Desktop.
Service for sharing state across controllers. Supports a notion of baseline states that can be rolled back to. You can also set (and sync to) new baselines.
angular.module('myModule').factory('SharedMetaData', function(SharedState) {
return SharedState.init({
what: 'Array Stuffs',
arr: [1,2,3,4]
});
});
angular.module('myModule').controller('SomeCtrl', function($scope, $q, SharedMetaData) {
$q.when(SharedMetaData()).then(function(smd) {
$scope.smd = smd;
});
});
angular.module('myModule').controller('SomeCtrl', function($scope, $q, SharedMetaData) {
var deferred = $q.defer();
deferred.promise.then(SharedMetaData.set);
$timeout(function() {
deferred.resolve({
what: 'new array stuffs',
arr: ['a', 'b', 'd']
})
}, 5000);
});
angular.module('myModule').factory('SharedState', function($q, $timeout) {
return {
init: function(defaults) {
var payload = {}
, deferred
, self = this;
defaults = defaults || {}; // You can set initial defaults here
var SharedState = function(init_args) {
if(deferred) { return deferred.promise; }
deferred = $q.defer();
$q.when(defaults).then(function() { // Might only be promised defaults.
// Set defaults if any init_args - makes sure the next time we reload
// we do so with the new set of defaults;
if(init_args) {
angular.forEach(init_args, function(val, key) {
defaults[key] = val;
});
}
// Do something with init_args?
angular.forEach(defaults, function(val, key) {
payload[key] = angular.copy(val);
});
// Make good on our promises
deferred.resolve(payload);
});
return deferred.promise;
};
SharedState.reload = function() {
deferred = null;
return SharedState.apply(self, arguments);
};
return SharedState;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment