Merge branch 'master' of github.com:grevory/angular-local-storage into regex_clear

Conflicts:
	angular-local-storage.js
revert-117-master
Matthew Wickman 11 years ago
commit 04b3c77257

@ -10,35 +10,42 @@ module.exports = function(grunt) {
grunt.initConfig({ grunt.initConfig({
karma: { karma: {
options: { options: {
autowatch: false, autowatch: true,
browsers: [ browsers: [
'PhantomJS' 'PhantomJS'
], ],
configFile: 'test/karma.conf.js', configFile: 'test/karma.conf.js',
reporters: [ 'dots' ], reporters: ['dots'],
singleRun: true singleRun: false
}, },
unit: {} unit: {}
}, },
jshint: { jshint: {
grunt: { grunt: {
src: [ 'Gruntfile.js' ], src: ['Gruntfile.js'],
options: { options: {
node: true node: true
} }
}, },
dev: { dev: {
src: [ 'angular-local-storage.js' ], src: ['angular-local-storage.js'],
options: { options: {
jshintrc: '.jshintrc', jshintrc: '.jshintrc',
} }
}, },
test: { test: {
src: [ 'test/spec/**/*.js' ], src: ['test/spec/**/*.js'],
options: { options: {
jshintrc: 'test/.jshintrc', jshintrc: 'test/.jshintrc',
} }
} }
},
uglify: {
dist: {
files: {
'angular-local-storage.min.js': 'angular-local-storage.js'
}
}
} }
}); });
@ -50,4 +57,8 @@ module.exports = function(grunt) {
'jshint', 'jshint',
'test' 'test'
]); ]);
grunt.registerTask('dist', [
'uglify'
]);
}; };

@ -1,277 +1,313 @@
(function() { (function() {
/* Start angularLocalStorage */ /* Start angularLocalStorage */
'use strict';
var angularLocalStorage = angular.module('LocalStorageModule', []); var angularLocalStorage = angular.module('LocalStorageModule', []);
// You should set a prefix to avoid overwriting any local storage variables from the rest of your app angularLocalStorage.provider('localStorageService', function(){
// e.g. angularLocalStorage.constant('prefix', 'youAppName'); // You should set a prefix to avoid overwriting any local storage variables from the rest of your app
angularLocalStorage.value('prefix', 'ls'); // e.g. angularLocalStorage.constant('prefix', 'youAppName');
// Cookie options (usually in case of fallback) this.prefix = 'ls';
// expiry = Number of days before cookies expire // 0 = Does not expire // Cookie options (usually in case of fallback)
// path = The web path the cookie represents // expiry = Number of days before cookies expire // 0 = Does not expire
angularLocalStorage.constant('cookie', { expiry:30, path: '/'}); // path = The web path the cookie represents
angularLocalStorage.constant('notify', { setItem: true, removeItem: false} ); this.cookie = {
expiry: 30,
angularLocalStorage.service('localStorageService', [ path: '/'
'$rootScope', };
'prefix', this.notify = {
'cookie', setItem: true,
'notify', removeItem: false
function($rootScope, prefix, cookie, notify) { };
this.setPrefix = function(prefix){
// If there is a prefix set in the config lets use that with an appended period for readability this.prefix = prefix;
//var prefix = angularLocalStorage.constant; };
if (prefix.substr(-1)!=='.') { this.setStorageCookie = function(exp, path){
prefix = !!prefix ? prefix + '.' : ''; this.cookie = {
} expiry: exp,
path: path
// Checks the browser to see if local storage is supported };
var browserSupportsLocalStorage = function () { };
try { this.setNotify = function(itemSet, itemRemove){
return ('localStorage' in window && window['localStorage'] !== null); this.notify = {
} catch (e) { setItem: itemSet,
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message); removeItem: itemRemove
return false; };
}
}; };
// Directly adds a value to local storage this.$get = ['$rootScope', function($rootScope){
// 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 var prefix = this.prefix;
if (!browserSupportsLocalStorage()) { // If there is a prefix set in the config lets use that with an appended period for readability
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); if (prefix.substr(-1) !== '.') {
if (notify.setItem) { prefix = !!prefix ? prefix + '.' : '';
$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 // Checks the browser to see if local storage is supported
if (typeof value == "undefined") { var browserSupportsLocalStorage = function () {
value = null; 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
// 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);
}
try { return true;
if (angular.isObject(value) || angular.isArray(value)) { } catch (e) {
value = angular.toJson(value); $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
} }
localStorage.setItem(prefix+key, value); };
if (notify.setItem) {
$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'}); // 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);
} }
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return addToCookies(key, value);
}
return true;
};
// Directly get a value from local storage // Let's convert undefined values to null to get the value consistent
// Example use: localStorageService.get('library'); // returns 'angular' if (typeof value === "undefined") {
var getFromLocalStorage = function (key) { value = null;
if (!browserSupportsLocalStorage()) { }
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
return getFromCookies(key);
}
var item = localStorage.getItem(prefix+key); try {
// angular.toJson will convert null to 'null', so a proper conversion is needed if (angular.isObject(value) || angular.isArray(value)) {
// FIXME not a perfect solution, since a valid 'null' string can't be stored value = angular.toJson(value);
if (!item || item === 'null') return null; }
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;
};
if (item.charAt(0) === "{" || item.charAt(0) === "[") { // Directly get a value from local storage
return angular.fromJson(item); // Example use: localStorageService.get('library'); // returns 'angular'
} var getFromLocalStorage = function (key) {
return item;
};
// Remove an item from local storage if (!browserSupportsLocalStorage()) {
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular' $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
var removeFromLocalStorage = function (key) { return getFromCookies(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 { var item = localStorage.getItem(prefix + key);
localStorage.removeItem(prefix+key); // angular.toJson will convert null to 'null', so a proper conversion is needed
if (notify.removeItem) { // FIXME not a perfect solution, since a valid 'null' string can't be stored
$rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'}); if (!item || item === 'null') {
return null;
} }
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return removeFromCookies(key);
}
return true;
};
// Return array of keys for local storage if (item.charAt(0) === "{" || item.charAt(0) === "[") {
// Example use: var keys = localStorageService.keys() return angular.fromJson(item);
var getKeysForLocalStorage = function () { }
if (!browserSupportsLocalStorage()) { return item;
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED'); };
return false;
}
var prefixLength = prefix.length; // Remove an item from local storage
var keys = []; // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
for (var key in localStorage) { var removeFromLocalStorage = function (key) {
// Only return keys that are for this app if (!browserSupportsLocalStorage()) {
if (key.substr(0,prefixLength) === prefix) { $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
try { if (notify.removeItem) {
keys.push(key.substr(prefixLength)); $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.Description);
return [];
} }
return removeFromCookies(key);
} }
}
return keys;
};
// Remove all data for this app from local storage try {
// Also takes a regular expression string and removes the matching keys-value pairs localStorage.removeItem(prefix+key);
// Example use: localStorageService.clearAll(); if (notify.removeItem) {
// Should be used mostly for development purposes $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'});
var clearAllFromLocalStorage = function (regular_expression) {
var regular_expression = regular_expression || "";
//accounting for the '.' in the prefix when creating a regex
var temp_prefix = prefix.slice(0, -1) + "\.";
//regex to test the local storage keys against
var testregex = RegExp(temp_prefix + regular_expression);
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 and match the regular expression
if (testregex.test(key)) {
try {
removeFromLocalStorage(key.substr(prefixLength));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return clearAllFromCookies();
} }
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return removeFromCookies(key);
} }
} return true;
return true; };
};
// Checks the browser to see if cookies are supported // Return array of keys for local storage
var browserSupportsCookies = function() { // Example use: var keys = localStorageService.keys()
try { var getKeysForLocalStorage = function () {
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 if (!browserSupportsLocalStorage()) {
// Typically used as a fallback is local storage is not available in the browser $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
// Example use: localStorageService.cookie.add('library','angular'); return false;
var addToCookies = function (key, value) { }
if (typeof value == "undefined") {
return false;
}
if (!browserSupportsCookies()) { var prefixLength = prefix.length;
$rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED'); var keys = [];
return false; 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
// Also optionally takes a regular expression string and removes the matching key-value pairs
// Example use: localStorageService.clearAll();
// Should be used mostly for development purposes
var clearAllFromLocalStorage = function (regularExpression) {
var regularExpression = regularExpression || "";
//accounting for the '.' in the prefix when creating a regex
var tempPrefix = prefix.slice(0, -1) + "\.";
var testRegex = RegExp(tempPrefix + regularExpression);
if (!browserSupportsLocalStorage()) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
return clearAllFromCookies();
}
try { var prefixLength = prefix.length;
var expiry = '', expiryDate = new Date();
if (value === null) { for (var key in localStorage) {
// Mark that the cookie has expired one day ago // Only remove items that are for this app and match the regular expression
expiryDate.setTime(expiryDate.getTime() + (-1 * 24*60*60*1000)); if (testRegex.test(key)) {
expiry = "; expires="+expiryDate.toGMTString(); try {
removeFromLocalStorage(key.substr(prefixLength));
value = ''; } catch (e) {
} else if (cookie.expiry !== 0) { $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000)); return clearAllFromCookies();
expiry = "; expires="+expiryDate.toGMTString(); }
}
} }
if (!!key) { return true;
document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path; };
// 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;
} }
} catch (e) { };
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return false;
}
return true;
};
// Directly get a value from a cookie // Directly adds a value to cookies
// Example use: localStorageService.cookie.get('library'); // returns 'angular' // Typically used as a fallback is local storage is not available in the browser
var getFromCookies = function (key) { // Example use: localStorageService.cookie.add('library','angular');
if (!browserSupportsCookies()) { var addToCookies = function (key, value) {
$rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
return false;
}
var cookies = document.cookie.split(';'); if (typeof value === "undefined") {
for(var i=0;i < cookies.length;i++) { return false;
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) { if (!browserSupportsCookies()) {
addToCookies(key,null); $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
}; return false;
}
var clearAllFromCookies = function () { try {
var thisCookie = null, thisKey = null; var expiry = '',
var prefixLength = prefix.length; expiryDate = new Date();
var cookies = document.cookie.split(';');
for(var i=0;i < cookies.length;i++) { if (value === null) {
thisCookie = cookies[i]; // Mark that the cookie has expired one day ago
while (thisCookie.charAt(0)==' ') { expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
thisCookie = thisCookie.substring(1,thisCookie.length); 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;
} }
key = thisCookie.substring(prefixLength,thisCookie.indexOf('='));
removeFromCookies(key);
}
};
return { var cookies = document.cookie.split(';');
isSupported: browserSupportsLocalStorage, for(var i=0;i < cookies.length;i++) {
set: addToLocalStorage, var thisCookie = cookies[i];
add: addToLocalStorage, //DEPRECATED while (thisCookie.charAt(0)===' ') {
get: getFromLocalStorage, thisCookie = thisCookie.substring(1,thisCookie.length);
keys: getKeysForLocalStorage, }
remove: removeFromLocalStorage, if (thisCookie.indexOf(prefix + key + '=') === 0) {
clearAll: clearAllFromLocalStorage, return decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length));
cookie: { }
set: addToCookies, }
add: addToCookies, //DEPRECATED return null;
get: getFromCookies, };
remove: removeFromCookies,
clearAll: clearAllFromCookies 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); }).call(this);

@ -0,0 +1 @@
(function(){"use strict";var a=angular.module("LocalStorageModule",[]);a.provider("localStorageService",function(){this.prefix="ls",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){this.prefix=a},this.setStorageCookie=function(a,b){this.cookie={expiry:a,path:b}},this.setNotify=function(a,b){this.notify={setItem:a,removeItem:b}},this.$get=["$rootScope",function(a){var b=this.prefix;"."!==b.substr(-1)&&(b=b?b+".":"");var c=function(){try{var c="localStorage"in window&&null!==window.localStorage,d=b+"__"+Math.round(1e7*Math.random());return c&&(localStorage.setItem(d,""),localStorage.removeItem(d)),!0}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.message),!1}},d=function(d,e){if(!c())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),notify.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:d,newvalue:e,storageType:"cookie"}),j(d,e);"undefined"==typeof e&&(e=null);try{(angular.isObject(e)||angular.isArray(e))&&(e=angular.toJson(e)),localStorage.setItem(b+d,e),notify.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:d,newvalue:e,storageType:"localStorage"})}catch(f){return a.$broadcast("LocalStorageModule.notification.error",f.message),j(d,e)}return!0},e=function(d){if(!c())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),k(d);var e=localStorage.getItem(b+d);return e&&"null"!==e?"{"===e.charAt(0)||"["===e.charAt(0)?angular.fromJson(e):e:null},f=function(d){if(!c())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),notify.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:d,storageType:"cookie"}),l(d);try{localStorage.removeItem(b+d),notify.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:d,storageType:"localStorage"})}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.message),l(d)}return!0},g=function(){if(!c())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var d=b.length,e=[];for(var f in localStorage)if(f.substr(0,d)===b)try{e.push(f.substr(d))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.Description),[]}return e},h=function(d){var d=d||"",e=b.slice(0,-1)+".",g=RegExp(e+d);if(!c())return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),m();var h=b.length;for(var i in localStorage)if(g.test(i))try{f(i.substr(h))}catch(j){return a.$broadcast("LocalStorageModule.notification.error",j.message),m()}return!0},i=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}},j=function(c,d){if("undefined"==typeof d)return!1;if(!i())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var e="",f=new Date;null===d?(f.setTime(f.getTime()+-864e5),e="; expires="+f.toGMTString(),d=""):0!==cookie.expiry&&(f.setTime(f.getTime()+24*cookie.expiry*60*60*1e3),e="; expires="+f.toGMTString()),c&&(document.cookie=b+c+"="+encodeURIComponent(d)+e+"; path="+cookie.path)}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),!1}return!0},k=function(c){if(!i())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var d=document.cookie.split(";"),e=0;e<d.length;e++){for(var f=d[e];" "===f.charAt(0);)f=f.substring(1,f.length);if(0===f.indexOf(b+c+"="))return decodeURIComponent(f.substring(b.length+c.length+1,f.length))}return null},l=function(a){j(a,null)},m=function(){for(var a=null,c=b.length,d=document.cookie.split(";"),e=0;e<d.length;e++){for(a=d[e];" "===a.charAt(0);)a=a.substring(1,a.length);key=a.substring(c,a.indexOf("=")),l(key)}};return{isSupported:c,set:d,add:d,get:e,keys:g,remove:f,clearAll:h,cookie:{set:j,add:j,get:k,remove:l,clearAll:m}}}]})}).call(this);

@ -1,6 +1,6 @@
{ {
"name": "angular-local-storage", "name": "angular-local-storage",
"version": "0.0.1", "version": "0.0.2",
"homepage": "http://gregpike.net/demos/angular-local-storage/demo.html", "homepage": "http://gregpike.net/demos/angular-local-storage/demo.html",
"authors": [ "authors": [
"grevory <greg@gregpike.ca>" "grevory <greg@gregpike.ca>"
@ -21,6 +21,6 @@
], ],
"devDependencies": { "devDependencies": {
"angularjs": "*", "angularjs": "*",
"angular-mocks": "~1.0.8" "angular-mocks": "~1.2.1"
} }
} }

@ -1,6 +1,6 @@
{ {
"name": "angular-local-storage", "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", "description": "An Angular module that gives you access to the browsers local storage",
"main": "angular-local-storage.js", "main": "angular-local-storage.js",
"scripts": { "scripts": {
@ -27,7 +27,8 @@
"devDependencies": { "devDependencies": {
"time-grunt": "~0.1.1", "time-grunt": "~0.1.1",
"load-grunt-tasks": "~0.1.0", "load-grunt-tasks": "~0.1.0",
"grunt-karma": "~0.6.2", "grunt-contrib-jshint": "~0.6.4",
"grunt-contrib-jshint": "~0.6.4" "grunt": "~0.4.2",
"grunt-contrib-uglify": "~0.2.7"
} }
} }

@ -1,12 +1,55 @@
describe('Module: LocalStorageModule', function() { describe('Tests functionality of the localStorage module', function(){
'use strict'; 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];
}
});
// Load the Angular module spyOn(ls, 'set').andCallFake(function(key, val){
beforeEach(module('LocalStorageModule')); if(angular.isObject(val) || angular.isArray(val)){
val = angular.toJson(val);
}
if(angular.isNumber(val)){
val = val.toString();
}
return store[key] = val;
});
describe('constants', function() { spyOn(ls, 'clearAll').andCallFake(function(){
it('reads the constants', function() { store = {};
expect(true).toBe(true); return store;
});
}));
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' };
ls.set('object', obj);
var res = ls.get('object');
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');
}); });
}); });
});