-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalStorageModule.js
More file actions
94 lines (90 loc) · 2.17 KB
/
localStorageModule.js
File metadata and controls
94 lines (90 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var appModule = angular.module('localStorageModule', []);
appModule.factory('localStorageService', ['$window', function ($window) {
var storage = (angular.isUndefined($window.localStorage)) ? undefined : $window.localStorage, isSupported = !(angular.isUndefined(storage) || angular.isUndefined($window.JSON));
var privateStorage = {
//use this function to get pased and useable data from storage.
parseValue: function (res) {
var val;
try {
val = JSON.parse(res);
if (angular.isUndefined(val)) {
val = res;
}
if (val == 'true') {
val = true;
}
if (val == 'false') {
val = false;
}
if (parseFloat(val) == val && !angular.isObject(val)) {
val = parseFloat(val);
}
} catch (e) {
val = res;
}
return val;
},
getStorageKey: function (key, prefix) {
return prefix + key;
},
};
function publicStorage() {
this.prefix = "";
this.getStorageKey = function(key) {
return this.prefix + key;
};
this.set = function (key, value) {
if (!isSupported) {
try {
$.cookie(this.getStorageKey(key), value);
return value;
} catch (e) {
throw new Error('Local Storage not supported, make sure you have the $.cookie supported.');
}
}
var saver = JSON.stringify(value);
storage.setItem(this.getStorageKey(key), value);
return privateStorage.parseValue(saver);
};
this.get = function (key) {
if (!isSupported) {
try {
return privateStorage.parseValue($.cookie(this.getStorageKey(key)));
} catch (e) {
return null;
}
}
var item = storage.getItem(this.getStorageKey(key));
return privateStorage.parseValue(item);
};
this.remove = function (key) {
if (!isSupported) {
try {
$.cookie(this.getStorageKey(key), null);
return true;
} catch (e) {
return false;
}
}
storage.removeItem(this.getStorageKey(key));
return true;
};
this.removeAll = function () {
if (!isSupported) {
try {
$.cookie(this.getStorageKey(key), null);
return true;
} catch (e) {
return false;
}
}
storage.clear();
return true;
};
}
return {
create: function () {
return new publicStorage();
}
};
}]);