-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathangular-localstorage
More file actions
67 lines (63 loc) · 2.02 KB
/
angular-localstorage
File metadata and controls
67 lines (63 loc) · 2.02 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
angular.module('sLocalStorage', []).factory('sLocalStorage', function () {
var _ = window._;
var _storage = {
_prefix: 'prefix_',
_debug: true,
check: function () {
return _.isUndefined(localStorage) ? false : true;
},
get: function (key) {
if (!this.check()) return;
return this.onGet(localStorage.getItem(this._key(key)));
},
getAll: function () {
if (!this.check()) return ({});
var self = this;
var items = _.map(_.keys(localStorage), function (key) {
return self.get(key);
});
return items;
},
set: function (key, value) {
if (!this.check()) return;
try {
this.remove(key);
localStorage.setItem(this._key(key), this.onSet(value));
return true;
} catch (e) {
return false;
}
},
remove: function (key) {
if (!this.check()) return;
localStorage.removeItem(this._key(key));
},
removeByKeyContains: function (key) {
if (!this.check()) return;
_.each(_.keys(localStorage), function (e) {
e.indexOf(key) >= 0 && this.remove(e);
}, this);
},
clear: function () {
if (!this.check()) return;
localStorage.clear();
},
onSet: function (value) {
return _.isFunction(value) ? null : _.isObject(value) || _.isArray(value) ? JSON.stringify(value) : value;
},
onGet: function (value) {
try {
value = JSON.parse(value)
} catch (e) {
if (this._debug) {
console.error(e);
}
}
return value;
},
_key: function (key) {
return this._prefix + (_.isArray(key) || _.isObject(key) ? key.join(".") : key);
}
};
return _storage;
});