Skip to content

Instantly share code, notes, and snippets.

@dts dts/stately.js
Last active Sep 7, 2016

Embed
What would you like to do?
"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
You can’t perform that action at this time.