Last active
June 24, 2016 21:37
-
-
Save brettpennings/ae5d34de0961eef010c6 to your computer and use it in GitHub Desktop.
Service for Restoring Scope: this one uses $location instead of $route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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