diff --git a/demo-app.js b/demo-app.js index 46fc18f..1922610 100644 --- a/demo-app.js +++ b/demo-app.js @@ -6,5 +6,4 @@ var DemoCtrl = function($scope, localStorageService) { localStorageService.add('localStorageDemo',value); $scope.localStorageDemoValue = localStorageService.get('localStorageDemo'); }); - -}; \ No newline at end of file +}; diff --git a/localStorageModule.js b/localStorageModule.js index 8645618..3567a4d 100644 --- a/localStorageModule.js +++ b/localStorageModule.js @@ -121,7 +121,7 @@ angularLocalStorage.service('localStorageService', [ $rootScope.$broadcast('LocalStorageModule.notification.error',e.Description); return false; } - } + }; // Directly adds a value to cookies // Typically used as a fallback is local storage is not available in the browser @@ -176,7 +176,7 @@ angularLocalStorage.service('localStorageService', [ var removeFromCookies = function (key) { addToCookies(key,null); - } + }; var clearAllFromCookies = function () { var thisCookie = null, thisKey = null; @@ -190,8 +190,33 @@ angularLocalStorage.service('localStorageService', [ key = thisCookie.substring(prefixLength,thisCookie.indexOf('=')); removeFromCookies(key); } - } + }; + // JSON stringify functions based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON + var stringifyJson = function (vContent, isJSON) { + // If this is only a string and not a string in a recursive run of an object then let's return the string unadulterated + if (typeof vContent === "string" && vContent.charAt(0) !== "{" && !isJSON) { + return vContent; + } + if (vContent instanceof Object) { + var sOutput = ""; + if (vContent.constructor === Array) { + for (var nId = 0; nId < vContent.length; sOutput += this.stringifyJson(vContent[nId], true) + ",", nId++); + return "[" + sOutput.substr(0, sOutput.length - 1) + "]"; + } + if (vContent.toString !== Object.prototype.toString) { return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\""; } + for (var sProp in vContent) { sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringifyJson(vContent[sProp], true) + ","; } + return "{" + sOutput.substr(0, sOutput.length - 1) + "}"; + } + return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent); + }; + + var parseJson = function (sJSON) { + if (sJSON.charAt(0)!=='{') { + return sJSON; + } + return eval("(" + sJSON + ")"); + }; return { isSupported: browserSupportsLocalStorage, @@ -199,6 +224,8 @@ angularLocalStorage.service('localStorageService', [ get: getFromLocalStorage, remove: removeFromLocalStorage, clearAll: clearAllFromLocalStorage, + stringifyJson: stringifyJson, + parseJson: parseJson, cookie: { add: addToCookies, get: getFromCookies,