Skip to content

Instantly share code, notes, and snippets.

@brettpennings
Last active June 24, 2016 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettpennings/ae5d34de0961eef010c6 to your computer and use it in GitHub Desktop.
Save brettpennings/ae5d34de0961eef010c6 to your computer and use it in GitHub Desktop.
Service for Restoring Scope: this one uses $location instead of $route
angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$location', function ($rootScope, $location) {
var currentScope = null;
var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
if (storedScope[name] == null) {
storedScope[name] = defaultValue;
}
scope[name] = storedScope[name];
}
var service = {
GetOrRegisterScopeVariables: function (names, defaultValues, scope) {
currentScope = scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
if (storedBaseScope == null) {
storedBaseScope = {};
}
// stored scope is indexed by route name
var storedScope = storedBaseScope[$location.url()];
if (storedScope == null) {
storedScope = {};
}
if (typeof names === "string") {
getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
} else if (Array.isArray(names)) {
angular.forEach(names, function (name, i) {
getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
});
} else {
console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
}
// save stored scope back off
storedBaseScope[$location.url()] = storedScope;
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
},
SaveState: function () {
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
// save off scope based on registered indexes
angular.forEach(storedBaseScope[$location.url()], function (item, i) {
storedBaseScope[$location.url()][i] = currentScope[i];
});
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
}
}
$rootScope.$on("savestate", service.SaveState);
return service;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment