UNPKG

4.02 kBJavaScriptView Raw
1(function (ng, localStorage) {
2 /**
3 * @ngdoc service
4 * @module apeman-ui-contrib-angular-storaging
5 * @name apStorage
6 * @description
7 * Local storage wrapper.
8 */
9
10 "use strict";
11
12 ng
13 .module('apeman-ui-contrib-angular-storaging')
14 .service("apStorage", function () {
15 var s = this;
16
17 /**
18 * @ngdoc method
19 * @name apStorage#get
20 * @description Get data with key from local storage.
21 * @param {string} key - Key for storage.
22 * @returns {object|string|null} - Acquired value.
23 */
24 s.get = function get(key) {
25 var s = this;
26 return s.getObj(key) || s.getStr(key) || null;
27 };
28 /**
29 * @ngdoc method
30 * @name apStorage#getObj
31 * @description Get value as an object.
32 * @param {string} key - Key for storage.
33 * @returns {object|null} - Acquired value.
34 */
35 s.getObj = function getObj(key) {
36 var s = this,
37 val = s._getItem(key);
38 try {
39 return JSON.parse(val);
40 } catch (e) {
41 // Ignore error.
42 return null;
43 }
44 };
45 /**
46 * @ngdoc method
47 * @name apStorage#getStr
48 * @description Get value as string.
49 * @param {string} key - Key for storage.
50 * @returns {string|null} - Acquired value.
51 */
52 s.getStr = function getStr(key) {
53 var s = this,
54 val = s._getItem(key);
55 return val && String(val) || null;
56 };
57 /**
58 * @ngdoc method
59 * @name apStorage#set
60 * @description Set a value to save localstorage.
61 * @param {string} key - Key for storage.
62 * @param {string|object} val - Value to get.
63 */
64 s.set = function set(key, val) {
65 var s = this;
66 switch (typeof val) {
67 case 'object':
68 s.setObj(key, val);
69 break;
70 default:
71 s.setStr(key, val);
72 break;
73 }
74 };
75 /**
76 * @ngdoc method
77 * @name apStorage#remove
78 * @description Remove an item from localstorage.
79 * @param {string} key - Key to remove.
80 */
81 s.remove = function (key) {
82 var s = this;
83 s._removeItem(key);
84 };
85 /**
86 * @ngdoc method
87 * @name apStorage#setObj
88 * @description Set an object.
89 * @param {string} key - Key for storage.
90 * @param {object} obj - Object to set.
91 */
92 s.setObj = function (key, obj) {
93 var s = this;
94 try {
95 s._setItem(key, JSON.stringify(obj));
96 } catch (e) {
97 s._setItem(key, obj);
98 }
99 };
100 /**
101 * @ngdoc method
102 * @name apStorage#setStr
103 * @description Set string.
104 * @param {string} key - Key for storage.
105 * @param {string} str - String to save.
106 */
107 s.setStr = function (key, str) {
108 var s = this;
109 s._setItem(key, String(str));
110 };
111 s._getItem = function (key) {
112 return localStorage.getItem(key);
113 };
114 s._setItem = function (key, val) {
115 localStorage.setItem(key, val);
116 };
117 s._removeItem = function (key) {
118 localStorage.removeItem(key);
119 };
120 });
121})
122(angular, window.localStorage);