From 7354a44bae904ee3971bd898a62937eac7921c93 Mon Sep 17 00:00:00 2001 From: mwq27 Date: Sat, 2 Nov 2013 09:56:32 -0500 Subject: [PATCH 1/8] Update test.js --- test/spec/test.js | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/test/spec/test.js b/test/spec/test.js index 08cefc6..42bdad8 100644 --- a/test/spec/test.js +++ b/test/spec/test.js @@ -1,12 +1,25 @@ -describe('Module: LocalStorageModule', function() { - 'use strict'; +describe('Tests functionality of the localStorage module', function(){ + beforeEach(module('LocalStorageModule')); + var ls, store = {}; + beforeEach(inject(function(_localStorageService_){ + ls = _localStorageService_; - // Load the Angular module - beforeEach(module('LocalStorageModule')); + spyOn(ls, 'get').andCallFake(function(key){ + return store[key]; + }); - describe('constants', function() { - it('reads the constants', function() { - expect(true).toBe(true); + spyOn(ls, 'set').andCallFake(function(key, val){ + return store[key] = val + ''; + }); + + spyOn(ls, 'clearAll').andCallFake(function(){ + store = {}; + return store; + }); + })); + + it("Should add a value to my local storage", function(){ + ls.set('test', 'MyTest Value'); + expect(ls.get('test')).toBe('MyTest Value'); }); - }); }); From 650e9b825d14da14103f96b61e6e52062c851999 Mon Sep 17 00:00:00 2001 From: mwq27 Date: Sat, 2 Nov 2013 10:05:44 -0500 Subject: [PATCH 2/8] Update test.js --- test/spec/test.js | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/test/spec/test.js b/test/spec/test.js index 42bdad8..714c4da 100644 --- a/test/spec/test.js +++ b/test/spec/test.js @@ -5,11 +5,18 @@ describe('Tests functionality of the localStorage module', function(){ ls = _localStorageService_; spyOn(ls, 'get').andCallFake(function(key){ - return store[key]; + if(store[key].charAt(0) ==="{" || store[key].charAt(0) === "["){ + return angular.fromJson(store[key]); + }else{ + return store[key]; + } }); spyOn(ls, 'set').andCallFake(function(key, val){ - return store[key] = val + ''; + if(typeof val === "object"){ + val = angular.toJson(val); + } + return store[key] = val; }); spyOn(ls, 'clearAll').andCallFake(function(){ @@ -21,5 +28,11 @@ describe('Tests functionality of the localStorage module', function(){ it("Should add a value to my local storage", function(){ ls.set('test', 'MyTest Value'); expect(ls.get('test')).toBe('MyTest Value'); + + var obj = { key: 'val' }; + ls.set('object', obj); + var res = ls.get('object'); + expect(res.key).toBe('val'); + }); }); From e96a2b243522e0e237b84d6bb8a152bd06dd4a3e Mon Sep 17 00:00:00 2001 From: mwq27 Date: Sun, 3 Nov 2013 10:36:00 -0600 Subject: [PATCH 3/8] Added check if stored value is a number to spyOn, since localStorage will store integers as strings. --- test/spec/test.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/test/spec/test.js b/test/spec/test.js index 714c4da..1a520de 100644 --- a/test/spec/test.js +++ b/test/spec/test.js @@ -1,21 +1,25 @@ describe('Tests functionality of the localStorage module', function(){ beforeEach(module('LocalStorageModule')); - var ls, store = {}; + var ls, store = []; beforeEach(inject(function(_localStorageService_){ ls = _localStorageService_; spyOn(ls, 'get').andCallFake(function(key){ - if(store[key].charAt(0) ==="{" || store[key].charAt(0) === "["){ + if(store[key].charAt(0) === "{" || store[key].charAt(0) === "["){ return angular.fromJson(store[key]); }else{ return store[key]; } + }); spyOn(ls, 'set').andCallFake(function(key, val){ - if(typeof val === "object"){ + if(angular.isObject(val) || angular.isArray(val)){ val = angular.toJson(val); } + if(angular.isNumber(val)){ + val = val.toString(); + } return store[key] = val; }); @@ -26,8 +30,9 @@ describe('Tests functionality of the localStorage module', function(){ })); it("Should add a value to my local storage", function(){ - ls.set('test', 'MyTest Value'); - expect(ls.get('test')).toBe('MyTest Value'); + var n = 234; + ls.set('test', n); + expect(ls.get('test')).toBe('234'); var obj = { key: 'val' }; ls.set('object', obj); From 2bff9d3e3c4d17229b857a4854665c7e43539b35 Mon Sep 17 00:00:00 2001 From: Marques Woodson Date: Sun, 3 Nov 2013 12:19:07 -0600 Subject: [PATCH 4/8] Configured the service to a provider type for more configurability. --- Gruntfile.js | 4 +- angular-local-storage.js | 543 ++++++++++++++++++++------------------- test/spec/test.js | 20 +- 3 files changed, 298 insertions(+), 269 deletions(-) diff --git a/Gruntfile.js b/Gruntfile.js index b821fdd..28e43fc 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -10,13 +10,13 @@ module.exports = function(grunt) { grunt.initConfig({ karma: { options: { - autowatch: false, + autowatch: true, browsers: [ 'PhantomJS' ], configFile: 'test/karma.conf.js', reporters: [ 'dots' ], - singleRun: true + singleRun: false }, unit: {} }, diff --git a/angular-local-storage.js b/angular-local-storage.js index 6f23c6a..cb7c126 100644 --- a/angular-local-storage.js +++ b/angular-local-storage.js @@ -1,270 +1,287 @@ (function() { -/* Start angularLocalStorage */ - -var angularLocalStorage = angular.module('LocalStorageModule', []); + /* Start angularLocalStorage */ + 'use strict'; + var angularLocalStorage = angular.module('LocalStorageModule', []); + angularLocalStorage.provider('localStorageService', function(){ // You should set a prefix to avoid overwriting any local storage variables from the rest of your app // e.g. angularLocalStorage.constant('prefix', 'youAppName'); -angularLocalStorage.value('prefix', 'ls'); + this.prefix = 'ls'; // Cookie options (usually in case of fallback) // expiry = Number of days before cookies expire // 0 = Does not expire // path = The web path the cookie represents -angularLocalStorage.constant('cookie', { expiry:30, path: '/'}); -angularLocalStorage.constant('notify', { setItem: true, removeItem: false} ); - -angularLocalStorage.service('localStorageService', [ - '$rootScope', - 'prefix', - 'cookie', - 'notify', - function($rootScope, prefix, cookie, notify) { - - // If there is a prefix set in the config lets use that with an appended period for readability - //var prefix = angularLocalStorage.constant; - if (prefix.substr(-1)!=='.') { - prefix = !!prefix ? prefix + '.' : ''; - } - - // Checks the browser to see if local storage is supported - var browserSupportsLocalStorage = function () { - try { - return ('localStorage' in window && window['localStorage'] !== null); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return false; - } - }; - - // 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) { - - // If this browser does not support local storage use cookies - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - if (notify.setItem) { - $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'}); - } - return addToCookies(key, value); - } - - // Let's convert undefined values to null to get the value consistent - if (typeof value == "undefined") { - value = null; - } - - try { - if (angular.isObject(value) || angular.isArray(value)) { - value = angular.toJson(value); - } - localStorage.setItem(prefix+key, value); - if (notify.setItem) { - $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'}); - } - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return addToCookies(key, value); - } - return true; - }; - - // Directly get a value from local storage - // Example use: localStorageService.get('library'); // returns 'angular' - var getFromLocalStorage = function (key) { - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - return getFromCookies(key); - } - - var item = localStorage.getItem(prefix+key); - // angular.toJson will convert null to 'null', so a proper conversion is needed - // FIXME not a perfect solution, since a valid 'null' string can't be stored - if (!item || item === 'null') return null; - - if (item.charAt(0) === "{" || item.charAt(0) === "[") { - return angular.fromJson(item); - } - return item; - }; - - // Remove an item from local storage - // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular' - var removeFromLocalStorage = function (key) { - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - if (notify.removeItem) { - $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'}); - } - return removeFromCookies(key); - } - - try { - localStorage.removeItem(prefix+key); - if (notify.removeItem) { - $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'}); - } - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return removeFromCookies(key); - } - return true; - }; - - // Return array of keys for local storage - // Example use: var keys = localStorageService.keys() - var getKeysForLocalStorage = function () { - - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - return false; - } - - var prefixLength = prefix.length; - var keys = []; - for (var key in localStorage) { - // Only return keys that are for this app - if (key.substr(0,prefixLength) === prefix) { - try { - keys.push(key.substr(prefixLength)); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.Description); - return []; - } - } - } - return keys; - }; - - // Remove all data for this app from local storage - // Example use: localStorageService.clearAll(); - // Should be used mostly for development purposes - var clearAllFromLocalStorage = function () { - - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - return clearAllFromCookies(); - } - - var prefixLength = prefix.length; - - for (var key in localStorage) { - // Only remove items that are for this app - if (key.substr(0,prefixLength) === prefix) { - try { - removeFromLocalStorage(key.substr(prefixLength)); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return clearAllFromCookies(); - } - } - } - return true; - }; - - // Checks the browser to see if cookies are supported - var browserSupportsCookies = function() { - try { - return navigator.cookieEnabled || - ("cookie" in document && (document.cookie.length > 0 || - (document.cookie = "test").indexOf.call(document.cookie, "test") > -1)); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return false; - } - }; - - // Directly adds a value to cookies - // Typically used as a fallback is local storage is not available in the browser - // Example use: localStorageService.cookie.add('library','angular'); - var addToCookies = function (key, value) { - - if (typeof value == "undefined") { - return false; - } - - if (!browserSupportsCookies()) { - $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); - return false; - } - - try { - var expiry = '', expiryDate = new Date(); - if (value === null) { - // Mark that the cookie has expired one day ago - expiryDate.setTime(expiryDate.getTime() + (-1 * 24*60*60*1000)); - expiry = "; expires="+expiryDate.toGMTString(); - - value = ''; - } else if (cookie.expiry !== 0) { - expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000)); - expiry = "; expires="+expiryDate.toGMTString(); - } - if (!!key) { - document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path; - } - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return false; - } - return true; - }; - - // Directly get a value from a cookie - // Example use: localStorageService.cookie.get('library'); // returns 'angular' - var getFromCookies = function (key) { - if (!browserSupportsCookies()) { - $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); - return false; - } - - var cookies = document.cookie.split(';'); - for(var i=0;i < cookies.length;i++) { - var thisCookie = cookies[i]; - while (thisCookie.charAt(0)==' ') { - thisCookie = thisCookie.substring(1,thisCookie.length); - } - if (thisCookie.indexOf(prefix+key+'=') === 0) { - return decodeURIComponent(thisCookie.substring(prefix.length+key.length+1,thisCookie.length)); - } - } - return null; - }; - - var removeFromCookies = function (key) { - addToCookies(key,null); - }; - - var clearAllFromCookies = function () { - var thisCookie = null, thisKey = null; - var prefixLength = prefix.length; - var cookies = document.cookie.split(';'); - for(var i=0;i < cookies.length;i++) { - thisCookie = cookies[i]; - while (thisCookie.charAt(0)==' ') { - thisCookie = thisCookie.substring(1,thisCookie.length); - } - key = thisCookie.substring(prefixLength,thisCookie.indexOf('=')); - removeFromCookies(key); - } - }; - - return { - isSupported: browserSupportsLocalStorage, - set: addToLocalStorage, - add: addToLocalStorage, //DEPRECATED - get: getFromLocalStorage, - keys: getKeysForLocalStorage, - remove: removeFromLocalStorage, - clearAll: clearAllFromLocalStorage, - cookie: { - set: addToCookies, - add: addToCookies, //DEPRECATED - get: getFromCookies, - remove: removeFromCookies, - clearAll: clearAllFromCookies - } - }; - -}]); -}).call(this); + this.cookie = { + expiry: 30, + path: '/' + }; + this.notify = { + setItem: true, + removeItem: false + }; + this.setPrefix = function(prefix){ + this.prefix = prefix; + }; + this.setStorageCookie = function(exp, path){ + this.cookie = { + expiry: exp, + path: path + }; + }; + this.setNotify = function(itemSet, itemRemove){ + this.notify = { + setItem: itemSet, + removeItem: itemRemove + }; + }; + + this.$get = ['$rootScope',function($rootScope){ + var prefix = this.prefix; + // If there is a prefix set in the config lets use that with an appended period for readability + //var prefix = angularLocalStorage.constant; + if (prefix.substr(-1)!=='.') { + prefix = !!prefix ? prefix + '.' : ''; + } + + // Checks the browser to see if local storage is supported + var browserSupportsLocalStorage = function () { + try { + return ('localStorage' in window && window.localStorage !== null); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); + return false; + } + }; + + // 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) { + + // If this browser does not support local storage use cookies + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); + if (notify.setItem) { + $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'}); + } + return addToCookies(key, value); + } + + // Let's convert undefined values to null to get the value consistent + if (typeof value === "undefined") { + value = null; + } + + try { + if (angular.isObject(value) || angular.isArray(value)) { + value = angular.toJson(value); + } + localStorage.setItem(prefix+key, value); + if (notify.setItem) { + $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'}); + } + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); + return addToCookies(key, value); + } + return true; + }; + + // Directly get a value from local storage + // Example use: localStorageService.get('library'); // returns 'angular' + var getFromLocalStorage = function (key) { + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); + return getFromCookies(key); + } + + var item = localStorage.getItem(prefix+key); + // angular.toJson will convert null to 'null', so a proper conversion is needed + // FIXME not a perfect solution, since a valid 'null' string can't be stored + if (!item || item === 'null') {return null;} + + if (item.charAt(0) === "{" || item.charAt(0) === "[") { + return angular.fromJson(item); + } + return item; + }; + + // Remove an item from local storage + // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular' + var removeFromLocalStorage = function (key) { + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); + if (notify.removeItem) { + $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'}); + } + return removeFromCookies(key); + } + + try { + localStorage.removeItem(prefix+key); + if (notify.removeItem) { + $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'}); + } + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); + return removeFromCookies(key); + } + return true; + }; + + // Return array of keys for local storage + // Example use: var keys = localStorageService.keys() + var getKeysForLocalStorage = function () { + + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); + return false; + } + + var prefixLength = prefix.length; + var keys = []; + for (var key in localStorage) { + // Only return keys that are for this app + if (key.substr(0,prefixLength) === prefix) { + try { + keys.push(key.substr(prefixLength)); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.Description); + return []; + } + } + } + return keys; + }; + + // Remove all data for this app from local storage + // Example use: localStorageService.clearAll(); + // Should be used mostly for development purposes + var clearAllFromLocalStorage = function () { + + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); + return clearAllFromCookies(); + } + + var prefixLength = prefix.length; + + for (var key in localStorage) { + // Only remove items that are for this app + if (key.substr(0,prefixLength) === prefix) { + try { + removeFromLocalStorage(key.substr(prefixLength)); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); + return clearAllFromCookies(); + } + } + } + return true; + }; + + // Checks the browser to see if cookies are supported + var browserSupportsCookies = function() { + try { + return navigator.cookieEnabled || + ("cookie" in document && (document.cookie.length > 0 || + (document.cookie = "test").indexOf.call(document.cookie, "test") > -1)); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); + return false; + } + }; + + // Directly adds a value to cookies + // Typically used as a fallback is local storage is not available in the browser + // Example use: localStorageService.cookie.add('library','angular'); + var addToCookies = function (key, value) { + + if (typeof value === "undefined") { + return false; + } + + if (!browserSupportsCookies()) { + $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); + return false; + } + + try { + var expiry = '', expiryDate = new Date(); + if (value === null) { + // Mark that the cookie has expired one day ago + expiryDate.setTime(expiryDate.getTime() + (-1 * 24*60*60*1000)); + expiry = "; expires="+expiryDate.toGMTString(); + + value = ''; + } else if (cookie.expiry !== 0) { + expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000)); + expiry = "; expires="+expiryDate.toGMTString(); + } + if (!!key) { + document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path; + } + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); + return false; + } + return true; + }; + + // Directly get a value from a cookie + // Example use: localStorageService.cookie.get('library'); // returns 'angular' + var getFromCookies = function (key) { + if (!browserSupportsCookies()) { + $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); + return false; + } + + var cookies = document.cookie.split(';'); + for(var i=0;i < cookies.length;i++) { + var thisCookie = cookies[i]; + while (thisCookie.charAt(0)===' ') { + thisCookie = thisCookie.substring(1,thisCookie.length); + } + if (thisCookie.indexOf(prefix+key+'=') === 0) { + return decodeURIComponent(thisCookie.substring(prefix.length+key.length+1,thisCookie.length)); + } + } + return null; + }; + + var removeFromCookies = function (key) { + addToCookies(key,null); + }; + + var clearAllFromCookies = function () { + var thisCookie = null, thisKey = null; + var prefixLength = prefix.length; + var cookies = document.cookie.split(';'); + for(var i=0;i < cookies.length;i++) { + thisCookie = cookies[i]; + while (thisCookie.charAt(0)===' ') { + thisCookie = thisCookie.substring(1,thisCookie.length); + } + key = thisCookie.substring(prefixLength,thisCookie.indexOf('=')); + removeFromCookies(key); + } + }; + + return { + isSupported: browserSupportsLocalStorage, + set: addToLocalStorage, + add: addToLocalStorage, //DEPRECATED + get: getFromLocalStorage, + keys: getKeysForLocalStorage, + remove: removeFromLocalStorage, + clearAll: clearAllFromLocalStorage, + cookie: { + set: addToCookies, + add: addToCookies, //DEPRECATED + get: getFromCookies, + remove: removeFromCookies, + clearAll: clearAllFromCookies + } + }; + }] + }); +}).call(this); \ No newline at end of file diff --git a/test/spec/test.js b/test/spec/test.js index 1a520de..2a3af0a 100644 --- a/test/spec/test.js +++ b/test/spec/test.js @@ -1,16 +1,16 @@ describe('Tests functionality of the localStorage module', function(){ - beforeEach(module('LocalStorageModule')); + beforeEach(module('LocalStorageModule', function(localStorageServiceProvider){ + p = localStorageServiceProvider; + })); var ls, store = []; beforeEach(inject(function(_localStorageService_){ ls = _localStorageService_; - spyOn(ls, 'get').andCallFake(function(key){ if(store[key].charAt(0) === "{" || store[key].charAt(0) === "["){ return angular.fromJson(store[key]); }else{ return store[key]; } - }); spyOn(ls, 'set').andCallFake(function(key, val){ @@ -32,6 +32,7 @@ describe('Tests functionality of the localStorage module', function(){ it("Should add a value to my local storage", function(){ var n = 234; ls.set('test', n); + //Since localStorage makes the value a string, we look for the '234' and not 234 expect(ls.get('test')).toBe('234'); var obj = { key: 'val' }; @@ -40,4 +41,15 @@ describe('Tests functionality of the localStorage module', function(){ expect(res.key).toBe('val'); }); -}); + + it('Should allow me to set a prefix', function(){ + p.setPrefix("myPref"); + expect(p.prefix).toBe("myPref"); + }); + + it('Should allow me to set the cookie values', function(){ + p.setStorageCookie(60, '/path'); + expect(p.cookie.expiry).toBe(60); + expect(p.cookie.path).toBe('/path'); + }); +}); \ No newline at end of file From c0e86dc1bd3836e24f4b133314a72ec3dd914be2 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Thu, 21 Nov 2013 17:47:10 -0800 Subject: [PATCH 5/8] Fixes `QUOTA_EXCEEDED_ERR` error is private Safari window. --- angular-local-storage.js | 15 ++++++++++++++- bower.json | 4 ++-- package.json | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/angular-local-storage.js b/angular-local-storage.js index 6f23c6a..ca5be1d 100644 --- a/angular-local-storage.js +++ b/angular-local-storage.js @@ -28,7 +28,20 @@ angularLocalStorage.service('localStorageService', [ // Checks the browser to see if local storage is supported var browserSupportsLocalStorage = function () { try { - return ('localStorage' in window && window['localStorage'] !== null); + var supported = ('localStorage' in window && window['localStorage'] !== null); + + // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage + // is available, but trying to call .setItem throws an exception. + // + // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage + // that exceeded the quota." + var key = prefix + '__' + Math.round(Math.random() * 1e7); + if (supported) { + localStorage.setItem(key, ''); + localStorage.removeItem(key); + } + + return true; } catch (e) { $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); return false; diff --git a/bower.json b/bower.json index 337630e..cf45adc 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "angular-local-storage", - "version": "0.0.1", + "version": "0.0.2", "homepage": "http://gregpike.net/demos/angular-local-storage/demo.html", "authors": [ "grevory " @@ -21,6 +21,6 @@ ], "devDependencies": { "angularjs": "*", - "angular-mocks": "~1.0.8" + "angular-mocks": "~1.2.1" } } diff --git a/package.json b/package.json index e065a85..86c5717 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-local-storage", - "version": "0.0.1", + "version": "0.0.2", "description": "An Angular module that gives you access to the browsers local storage", "main": "angular-local-storage.js", "scripts": { From ab81628c93bb3ac64ea10916f103eb678f48af5b Mon Sep 17 00:00:00 2001 From: ehaozuo Date: Wed, 27 Nov 2013 09:09:39 +0800 Subject: [PATCH 6/8] add uglified version for users --- Gruntfile.js | 21 ++++++++++++++++----- angular-local-storage.min.js | 1 + package.json | 5 +++-- 3 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 angular-local-storage.min.js diff --git a/Gruntfile.js b/Gruntfile.js index b821fdd..dfaefbe 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -15,30 +15,37 @@ module.exports = function(grunt) { 'PhantomJS' ], configFile: 'test/karma.conf.js', - reporters: [ 'dots' ], + reporters: ['dots'], singleRun: true }, unit: {} }, jshint: { grunt: { - src: [ 'Gruntfile.js' ], + src: ['Gruntfile.js'], options: { node: true } }, dev: { - src: [ 'angular-local-storage.js' ], + src: ['angular-local-storage.js'], options: { jshintrc: '.jshintrc', } }, test: { - src: [ 'test/spec/**/*.js' ], + src: ['test/spec/**/*.js'], options: { jshintrc: 'test/.jshintrc', } } + }, + uglify: { + dist: { + files: { + 'angular-local-storage.min.js': 'angular-local-storage.js' + } + } } }); @@ -50,4 +57,8 @@ module.exports = function(grunt) { 'jshint', 'test' ]); -}; + + grunt.registerTask('dist', [ + 'uglify' + ]); +}; \ No newline at end of file diff --git a/angular-local-storage.min.js b/angular-local-storage.min.js new file mode 100644 index 0000000..6be610a --- /dev/null +++ b/angular-local-storage.min.js @@ -0,0 +1 @@ +(function(){var a=angular.module("LocalStorageModule",[]);a.value("prefix","ls"),a.constant("cookie",{expiry:30,path:"/"}),a.constant("notify",{setItem:!0,removeItem:!1}),a.service("localStorageService",["$rootScope","prefix","cookie","notify",function(a,b,c,d){"."!==b.substr(-1)&&(b=b?b+".":"");var e=function(){try{return"localStorage"in window&&null!==window.localStorage}catch(b){return a.$broadcast("LocalStorageModule.notification.error",b.message),!1}},f=function(c,f){if(!e())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),d.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:c,newvalue:f,storageType:"cookie"}),l(c,f);"undefined"==typeof f&&(f=null);try{(angular.isObject(f)||angular.isArray(f))&&(f=angular.toJson(f)),localStorage.setItem(b+c,f),d.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:c,newvalue:f,storageType:"localStorage"})}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),l(c,f)}return!0},g=function(c){if(!e())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),m(c);var d=localStorage.getItem(b+c);return d&&"null"!==d?"{"===d.charAt(0)||"["===d.charAt(0)?angular.fromJson(d):d:null},h=function(c){if(!e())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),d.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:c,storageType:"cookie"}),n(c);try{localStorage.removeItem(b+c),d.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:c,storageType:"localStorage"})}catch(f){return a.$broadcast("LocalStorageModule.notification.error",f.message),n(c)}return!0},i=function(){if(!e())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var c=b.length,d=[];for(var f in localStorage)if(f.substr(0,c)===b)try{d.push(f.substr(c))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.Description),[]}return d},j=function(){if(!e())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),o();var c=b.length;for(var d in localStorage)if(d.substr(0,c)===b)try{h(d.substr(c))}catch(f){return a.$broadcast("LocalStorageModule.notification.error",f.message),o()}return!0},k=function(){try{return navigator.cookieEnabled||"cookie"in document&&(document.cookie.length>0||(document.cookie="test").indexOf.call(document.cookie,"test")>-1)}catch(b){return a.$broadcast("LocalStorageModule.notification.error",b.message),!1}},l=function(d,e){if("undefined"==typeof e)return!1;if(!k())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var f="",g=new Date;null===e?(g.setTime(g.getTime()+-864e5),f="; expires="+g.toGMTString(),e=""):0!==c.expiry&&(g.setTime(g.getTime()+24*c.expiry*60*60*1e3),f="; expires="+g.toGMTString()),d&&(document.cookie=b+d+"="+encodeURIComponent(e)+f+"; path="+c.path)}catch(h){return a.$broadcast("LocalStorageModule.notification.error",h.message),!1}return!0},m=function(c){if(!k())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var d=document.cookie.split(";"),e=0;e Date: Wed, 27 Nov 2013 19:13:31 -0500 Subject: [PATCH 7/8] Started fixing spacing --- angular-local-storage.js | 110 ++++++++++++++++++--------------------- 1 file changed, 50 insertions(+), 60 deletions(-) diff --git a/angular-local-storage.js b/angular-local-storage.js index 5a7f9a4..326b5c3 100644 --- a/angular-local-storage.js +++ b/angular-local-storage.js @@ -1,60 +1,50 @@ (function() { - /* Start angularLocalStorage */ - 'use strict'; - var angularLocalStorage = angular.module('LocalStorageModule', []); - - angularLocalStorage.provider('localStorageService', function(){ -// You should set a prefix to avoid overwriting any local storage variables from the rest of your app -// e.g. angularLocalStorage.constant('prefix', 'youAppName'); - this.prefix = 'ls'; -// Cookie options (usually in case of fallback) -// expiry = Number of days before cookies expire // 0 = Does not expire -// path = The web path the cookie represents - this.cookie = { - expiry: 30, - path: '/' - }; - this.notify = { - setItem: true, - removeItem: false - }; - this.setPrefix = function(prefix){ - this.prefix = prefix; - }; - this.setStorageCookie = function(exp, path){ - this.cookie = { - expiry: exp, - path: path - }; - }; - this.setNotify = function(itemSet, itemRemove){ - this.notify = { - setItem: itemSet, - removeItem: itemRemove - }; - }; - - this.$get = ['$rootScope',function($rootScope){ - var prefix = this.prefix; - // If there is a prefix set in the config lets use that with an appended period for readability - //var prefix = angularLocalStorage.constant; - if (prefix.substr(-1)!=='.') { - prefix = !!prefix ? prefix + '.' : ''; - } - - // Checks the browser to see if local storage is supported - var browserSupportsLocalStorage = function () { - try { - return ('localStorage' in window && window.localStorage !== null); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return false; - } - }; +/* Start angularLocalStorage */ +'use strict'; +var angularLocalStorage = angular.module('LocalStorageModule', []); + +angularLocalStorage.provider('localStorageService', function(){ + // You should set a prefix to avoid overwriting any local storage variables from the rest of your app + // e.g. angularLocalStorage.constant('prefix', 'youAppName'); + this.prefix = 'ls'; + // Cookie options (usually in case of fallback) + // expiry = Number of days before cookies expire // 0 = Does not expire + // path = The web path the cookie represents + this.cookie = { + expiry: 30, + path: '/' + }; + this.notify = { + setItem: true, + removeItem: false + }; + this.setPrefix = function(prefix){ + this.prefix = prefix; + }; + this.setStorageCookie = function(exp, path){ + this.cookie = { + expiry: exp, + path: path + }; + }; + this.setNotify = function(itemSet, itemRemove){ + this.notify = { + setItem: itemSet, + removeItem: itemRemove + }; + }; + + this.$get = ['$rootScope',function($rootScope){ - // Checks the browser to see if local storage is supported - var browserSupportsLocalStorage = function () { - try { + var prefix = this.prefix; + // If there is a prefix set in the config lets use that with an appended period for readability + if (prefix.substr(-1)!=='.') { + prefix = !!prefix ? prefix + '.' : ''; + } + + // Checks the browser to see if local storage is supported + var browserSupportsLocalStorage = function () { + try { var supported = ('localStorage' in window && window['localStorage'] !== null); // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage @@ -64,16 +54,16 @@ // that exceeded the quota." var key = prefix + '__' + Math.round(Math.random() * 1e7); if (supported) { - localStorage.setItem(key, ''); - localStorage.removeItem(key); + localStorage.setItem(key, ''); + localStorage.removeItem(key); } return true; - } catch (e) { + } catch (e) { $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); return false; - } - }; + } + }; // If this browser does not support local storage use cookies if (!browserSupportsLocalStorage()) { From 91271179e739309b7a0e7b5a051be8b5eaddbfbe Mon Sep 17 00:00:00 2001 From: Gregory Pike Date: Wed, 27 Nov 2013 20:06:28 -0500 Subject: [PATCH 8/8] Fixed JS error from merge and changed spacing --- angular-local-storage.js | 472 ++++++++++++++++++++------------------- 1 file changed, 242 insertions(+), 230 deletions(-) diff --git a/angular-local-storage.js b/angular-local-storage.js index 326b5c3..70aa8f7 100644 --- a/angular-local-storage.js +++ b/angular-local-storage.js @@ -34,12 +34,12 @@ angularLocalStorage.provider('localStorageService', function(){ }; }; - this.$get = ['$rootScope',function($rootScope){ + this.$get = ['$rootScope', function($rootScope){ var prefix = this.prefix; // If there is a prefix set in the config lets use that with an appended period for readability - if (prefix.substr(-1)!=='.') { - prefix = !!prefix ? prefix + '.' : ''; + if (prefix.substr(-1) !== '.') { + prefix = !!prefix ? prefix + '.' : ''; } // Checks the browser to see if local storage is supported @@ -59,237 +59,249 @@ angularLocalStorage.provider('localStorageService', function(){ } return true; + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error', e.message); + return false; + } + }; + + // 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) { + + // If this browser does not support local storage use cookies + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED'); + if (notify.setItem) { + $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'}); + } + return addToCookies(key, value); + } + + // Let's convert undefined values to null to get the value consistent + if (typeof value === "undefined") { + value = null; + } + + try { + if (angular.isObject(value) || angular.isArray(value)) { + value = angular.toJson(value); + } + localStorage.setItem(prefix + key, value); + if (notify.setItem) { + $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'}); + } + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error', e.message); + return addToCookies(key, value); + } + return true; + }; + + // Directly get a value from local storage + // Example use: localStorageService.get('library'); // returns 'angular' + var getFromLocalStorage = function (key) { + + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); + return getFromCookies(key); + } + + var item = localStorage.getItem(prefix + key); + // angular.toJson will convert null to 'null', so a proper conversion is needed + // FIXME not a perfect solution, since a valid 'null' string can't be stored + if (!item || item === 'null') { + return null; + } + + if (item.charAt(0) === "{" || item.charAt(0) === "[") { + return angular.fromJson(item); + } + + return item; + }; + + // Remove an item from local storage + // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular' + var removeFromLocalStorage = function (key) { + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED'); + if (notify.removeItem) { + $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'}); + } + return removeFromCookies(key); + } + + try { + localStorage.removeItem(prefix+key); + if (notify.removeItem) { + $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'}); + } + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error', e.message); + return removeFromCookies(key); + } + return true; + }; + + // Return array of keys for local storage + // Example use: var keys = localStorageService.keys() + var getKeysForLocalStorage = function () { + + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED'); + return false; + } + + var prefixLength = prefix.length; + var keys = []; + for (var key in localStorage) { + // Only return keys that are for this app + if (key.substr(0,prefixLength) === prefix) { + try { + keys.push(key.substr(prefixLength)); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error', e.Description); + return []; + } + } + } + return keys; + }; + + // Remove all data for this app from local storage + // Example use: localStorageService.clearAll(); + // Should be used mostly for development purposes + var clearAllFromLocalStorage = function () { + + if (!browserSupportsLocalStorage()) { + $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED'); + return clearAllFromCookies(); + } + + var prefixLength = prefix.length; + + for (var key in localStorage) { + // Only remove items that are for this app + if (key.substr(0,prefixLength) === prefix) { + try { + removeFromLocalStorage(key.substr(prefixLength)); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error', e.message); + return clearAllFromCookies(); + } + } + } + return true; + }; + + // Checks the browser to see if cookies are supported + var browserSupportsCookies = function() { + try { + return navigator.cookieEnabled || + ("cookie" in document && (document.cookie.length > 0 || + (document.cookie = "test").indexOf.call(document.cookie, "test") > -1)); + } catch (e) { + $rootScope.$broadcast('LocalStorageModule.notification.error', e.message); + return false; + } + }; + + // Directly adds a value to cookies + // Typically used as a fallback is local storage is not available in the browser + // Example use: localStorageService.cookie.add('library','angular'); + var addToCookies = function (key, value) { + + if (typeof value === "undefined") { + return false; + } + + if (!browserSupportsCookies()) { + $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED'); + return false; + } + + try { + var expiry = '', + expiryDate = new Date(); + + if (value === null) { + // Mark that the cookie has expired one day ago + expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000)); + expiry = "; expires=" + expiryDate.toGMTString(); + value = ''; + } else if (cookie.expiry !== 0) { + expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000)); + expiry = "; expires=" + expiryDate.toGMTString(); + } + if (!!key) { + document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path; + } } catch (e) { $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); return false; } + return true; + }; + + // Directly get a value from a cookie + // Example use: localStorageService.cookie.get('library'); // returns 'angular' + var getFromCookies = function (key) { + if (!browserSupportsCookies()) { + $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED'); + return false; + } + + var cookies = document.cookie.split(';'); + for(var i=0;i < cookies.length;i++) { + var thisCookie = cookies[i]; + while (thisCookie.charAt(0)===' ') { + thisCookie = thisCookie.substring(1,thisCookie.length); + } + if (thisCookie.indexOf(prefix + key + '=') === 0) { + return decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length)); + } + } + return null; + }; + + var removeFromCookies = function (key) { + addToCookies(key,null); + }; + + var clearAllFromCookies = function () { + var thisCookie = null, thisKey = null; + var prefixLength = prefix.length; + var cookies = document.cookie.split(';'); + for(var i = 0; i < cookies.length; i++) { + thisCookie = cookies[i]; + + while (thisCookie.charAt(0) === ' ') { + thisCookie = thisCookie.substring(1, thisCookie.length); + } + + key = thisCookie.substring(prefixLength, thisCookie.indexOf('=')); + removeFromCookies(key); + } }; - // If this browser does not support local storage use cookies - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - if (notify.setItem) { - $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'}); - } - return addToCookies(key, value); - } - - // Let's convert undefined values to null to get the value consistent - if (typeof value === "undefined") { - value = null; - } - - try { - if (angular.isObject(value) || angular.isArray(value)) { - value = angular.toJson(value); - } - localStorage.setItem(prefix+key, value); - if (notify.setItem) { - $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'}); - } - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return addToCookies(key, value); - } - return true; - }; - - // Directly get a value from local storage - // Example use: localStorageService.get('library'); // returns 'angular' - var getFromLocalStorage = function (key) { - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - return getFromCookies(key); - } - - var item = localStorage.getItem(prefix+key); - // angular.toJson will convert null to 'null', so a proper conversion is needed - // FIXME not a perfect solution, since a valid 'null' string can't be stored - if (!item || item === 'null') {return null;} - - if (item.charAt(0) === "{" || item.charAt(0) === "[") { - return angular.fromJson(item); - } - return item; - }; - - // Remove an item from local storage - // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular' - var removeFromLocalStorage = function (key) { - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - if (notify.removeItem) { - $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'}); - } - return removeFromCookies(key); - } - - try { - localStorage.removeItem(prefix+key); - if (notify.removeItem) { - $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'}); - } - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return removeFromCookies(key); - } - return true; - }; - - // Return array of keys for local storage - // Example use: var keys = localStorageService.keys() - var getKeysForLocalStorage = function () { - - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - return false; - } - - var prefixLength = prefix.length; - var keys = []; - for (var key in localStorage) { - // Only return keys that are for this app - if (key.substr(0,prefixLength) === prefix) { - try { - keys.push(key.substr(prefixLength)); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.Description); - return []; - } - } - } - return keys; - }; - - // Remove all data for this app from local storage - // Example use: localStorageService.clearAll(); - // Should be used mostly for development purposes - var clearAllFromLocalStorage = function () { - - if (!browserSupportsLocalStorage()) { - $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); - return clearAllFromCookies(); - } - - var prefixLength = prefix.length; - - for (var key in localStorage) { - // Only remove items that are for this app - if (key.substr(0,prefixLength) === prefix) { - try { - removeFromLocalStorage(key.substr(prefixLength)); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return clearAllFromCookies(); - } - } - } - return true; - }; - - // Checks the browser to see if cookies are supported - var browserSupportsCookies = function() { - try { - return navigator.cookieEnabled || - ("cookie" in document && (document.cookie.length > 0 || - (document.cookie = "test").indexOf.call(document.cookie, "test") > -1)); - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return false; - } - }; - - // Directly adds a value to cookies - // Typically used as a fallback is local storage is not available in the browser - // Example use: localStorageService.cookie.add('library','angular'); - var addToCookies = function (key, value) { - - if (typeof value === "undefined") { - return false; - } - - if (!browserSupportsCookies()) { - $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); - return false; - } - - try { - var expiry = '', expiryDate = new Date(); - if (value === null) { - // Mark that the cookie has expired one day ago - expiryDate.setTime(expiryDate.getTime() + (-1 * 24*60*60*1000)); - expiry = "; expires="+expiryDate.toGMTString(); - - value = ''; - } else if (cookie.expiry !== 0) { - expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000)); - expiry = "; expires="+expiryDate.toGMTString(); - } - if (!!key) { - document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path; - } - } catch (e) { - $rootScope.$broadcast('LocalStorageModule.notification.error',e.message); - return false; - } - return true; - }; - - // Directly get a value from a cookie - // Example use: localStorageService.cookie.get('library'); // returns 'angular' - var getFromCookies = function (key) { - if (!browserSupportsCookies()) { - $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); - return false; - } - - var cookies = document.cookie.split(';'); - for(var i=0;i < cookies.length;i++) { - var thisCookie = cookies[i]; - while (thisCookie.charAt(0)===' ') { - thisCookie = thisCookie.substring(1,thisCookie.length); - } - if (thisCookie.indexOf(prefix+key+'=') === 0) { - return decodeURIComponent(thisCookie.substring(prefix.length+key.length+1,thisCookie.length)); - } - } - return null; - }; - - var removeFromCookies = function (key) { - addToCookies(key,null); - }; - - var clearAllFromCookies = function () { - var thisCookie = null, thisKey = null; - var prefixLength = prefix.length; - var cookies = document.cookie.split(';'); - for(var i=0;i < cookies.length;i++) { - thisCookie = cookies[i]; - while (thisCookie.charAt(0)===' ') { - thisCookie = thisCookie.substring(1,thisCookie.length); - } - key = thisCookie.substring(prefixLength,thisCookie.indexOf('=')); - removeFromCookies(key); - } - }; - - return { - isSupported: browserSupportsLocalStorage, - set: addToLocalStorage, - add: addToLocalStorage, //DEPRECATED - get: getFromLocalStorage, - keys: getKeysForLocalStorage, - remove: removeFromLocalStorage, - clearAll: clearAllFromLocalStorage, - cookie: { - set: addToCookies, - add: addToCookies, //DEPRECATED - get: getFromCookies, - remove: removeFromCookies, - clearAll: clearAllFromCookies - } - }; - }] - }); + return { + isSupported: browserSupportsLocalStorage, + set: addToLocalStorage, + add: addToLocalStorage, //DEPRECATED + get: getFromLocalStorage, + keys: getKeysForLocalStorage, + remove: removeFromLocalStorage, + clearAll: clearAllFromLocalStorage, + cookie: { + set: addToCookies, + add: addToCookies, //DEPRECATED + get: getFromCookies, + remove: removeFromCookies, + clearAll: clearAllFromCookies + } + }; + }] +}); }).call(this); \ No newline at end of file