Skip to content

Instantly share code, notes, and snippets.

@dts
Last active September 7, 2016 19:35
Show Gist options
  • Save dts/f41d723fb30ccf58c87723d67b772060 to your computer and use it in GitHub Desktop.
Save dts/f41d723fb30ccf58c87723d67b772060 to your computer and use it in GitHub Desktop.
"Stately" for Angular
// automatically stores any values in the root scope to localStorage,
// restoring them when you return to the angular app.
// Usage: Include 'stately' in your modules requirement list.
// Redefine the STATELY_KEY to a new variable to make multiple apps
// work on the same domain.
angular.module('stately', []).constant('STATELY_KEY', 'stately'). run(function($rootScope, STATELY_KEY) {
function restore() {
console.log('Attempting to restore state from "' + STATELY_KEY + '"');
var state = localStorage.getItem(STATELY_KEY);
if (state) {
state = JSON.parse(state);
for (var k in state) {
$rootScope[k] = state[k];
console.log('Restoring ' + k + ' to ', state[k]);
}
}
}
try {
restore();
} catch (x) {
console.error('Error restoring state: ', x);
}
function postDigest() {
var rootState = {};
for (var k in $rootScope) {
if (k.indexOf('$') == 0) continue;
var v = $rootScope[k];
if (typeof v == 'function') continue;
rootState[k] = v;
}
localStorage.setItem(STATELY_KEY, JSON.stringify(rootState));
}
var hasRegistered = false;
$rootScope.$watch(function() {
if (hasRegistered) return;
hasRegistered = true;
$rootScope.$$postDigest(function() {
hasRegistered = false;
postDigest();
});
});
$rootScope.resetEverything = function() {
for (var k in $rootScope) {
if (k.indexOf('$') == 0) continue;
var v = $rootScope[k];
if (typeof v != 'function')
delete $rootScope[k];
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment