Dynamically change the storage type from controller itself.
Looking to use both Local Storage as well as Session Storage. Iniitally Configured the module to use 'localstorage' localStorageServiceProvider.setStorageType('localStorage').
But What if I want to session storage somewhere in middle of the application.
There should be some setStorageType function which we can call from controller that dynamically change storage type.
I agree that this would be nice. A workaround might be to set the storage type to localStorage and then do something like this to clear storage when the session ends:
$window.onbeforeunload = function (e) { localStorageService.clearAll(); }
ask for this feature too. I want to store something in the local storage to persistent, but I also want something in session storage that will be deleted when the user close the window. I supports to add some api like
set(key, value ,storageType)
Desperately need this too, so cooked up this simple patch.
Right before a set, switch type with either of these: localStorageService.setStorageType('localStorage'); localStorageService.setStorageType('sessionStorage');
or use: set(key, value, storageType)
if storageType omitted, then previous type is used. Use setStorageType to reset, so the default for your project is not disturbed.
--- angular-local-storage.js +++ angular-local-storage.js @@ -100,7 +100,7 @@ return prefix + key; }; // Checks the browser to see if local storage is supported
-
var browserSupportsLocalStorage = (function () { -
var checkSupport = function () { try { var supported = (storageType in $window && $window[storageType] !== null);
@@ -122,12 +122,18 @@ $rootScope.$broadcast('LocalStorageModule.notification.error', e.message); return false; }
-
}()); -
}; -
var browserSupportsLocalStorage = checkSupport();// Directly adds a value to local storage // If local storage is not available in the browser use cookies // Example use: localStorageService.add('library','angular');
-
var addToLocalStorage = function (key, value) { -
var addToLocalStorage = function (key, value, type) { -
if (type) { -
setStorageType(type); -
} -
// Let's convert undefined values to null to get the value consistent if (isUndefined(value)) { value = null;@@ -388,6 +394,11 @@ return storageType; };
-
var setStorageType = function(type) { -
storageType = type; -
browserSupportsLocalStorage = checkSupport(); -
}; -
// Add a listener on scope variable to save its changes to local storage // Return a function which when called cancels binding var bindToScope = function(scope, key, def, lsKey) {@@ -423,6 +434,7 @@ return { isSupported: browserSupportsLocalStorage, getStorageType: getStorageType,
-
setStorageType: setStorageType, set: addToLocalStorage, add: addToLocalStorage, //DEPRECATED get: getFromLocalStorage,
the patch doesn't display as it should. (+ - are messed up)
#320 by @zpgu addresses this issue. I encourage you to review his changes before I accept the PR. Thanks for the feedback guys!