forked from gsklee/ngStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngStorage.js
111 lines (86 loc) · 3.5 KB
/
ngStorage.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'use strict';
(function() {
/**
* @ngdoc overview
* @name ngStorage
*/
angular.module('ngStorage', []).
/**
* @ngdoc object
* @name ngStorage.$localStorage
* @requires $rootScope
* @requires $browser
* @requires $window
*/
factory('$localStorage', _storageFactory('localStorage')).
/**
* @ngdoc object
* @name ngStorage.$sessionStorage
* @requires $rootScope
* @requires $browser
* @requires $window
*/
factory('$sessionStorage', _storageFactory('sessionStorage'));
function _storageFactory(storageType) {
return [
'$rootScope',
'$browser',
'$window',
function(
$rootScope,
$browser,
$window
){
var webStorage = $window[storageType],
$storage = {
$default: function(items) {
for (var k in items) {
angular.isDefined($storage[k]) || ($storage[k] = items[k]);
}
return $storage;
},
$reset: function(items) {
for (var k in $storage) {
'$' === k[0] || delete $storage[k];
}
return $storage.$default(items);
}
},
_last$storage;
// (#8) `i < webStorage.length` is needed for IE9
for (var i = 0, k; i < webStorage.length; i++) {
if (k = webStorage.key(i)) {
'ngStorage-' === k.slice(0, 10) && ($storage[k.slice(10)] = angular.fromJson(webStorage.getItem(k)));
}
}
_last$storage = angular.copy($storage);
$browser.addPollFn(function() {
if (!angular.equals($storage, _last$storage)) {
angular.forEach($storage, function(v, k) {
if (angular.isDefined(v) && '$' !== k[0]) {
// Remove $$hashKey and other things that cannot be stringified
$storage[k] = angular.fromJson(angular.toJson(v));
webStorage.setItem('ngStorage-' + k, angular.toJson(v));
}
delete _last$storage[k];
});
for (var k in _last$storage) {
webStorage.removeItem('ngStorage-' + k);
}
_last$storage = angular.copy($storage);
$rootScope.$apply();
}
});
// (#6) Use `$window.addEventListener` instead of `angular.element` to avoid the jQuery-specific `event.originalEvent`
'localStorage' === storageType && $window.addEventListener('storage', function(event) {
if ('ngStorage-' === event.key.slice(0, 10)) {
event.newValue ? $storage[event.key.slice(10)] = angular.fromJson(event.newValue) : delete $storage[event.key.slice(10)];
_last$storage = angular.copy($storage);
$rootScope.$apply();
}
});
return $storage;
}
];
}
})();