Skip to content

Instantly share code, notes, and snippets.

@lleitep3
Created July 20, 2015 19:34
Show Gist options
  • Save lleitep3/d3609e98d8de3f025669 to your computer and use it in GitHub Desktop.
Save lleitep3/d3609e98d8de3f025669 to your computer and use it in GitHub Desktop.
serviço de acesso ao localStorage
angular.module('starter.services', [])
.service('$storage', function () {
this.get = function (key) {
var arrK = key.split('.'),
first = arrK.shift(),
result = JSON.parse(localStorage.getItem(first));
if (arrK.length === 0) {
return result;
}
for (k in arrK) {
if (result[arrK[k]] == undefined) return undefined;
result = result[arrK[k]];
}
return result;
};
this.set = function (key, value) {
var arrK = key.split('.'),
first = arrK.shift(),
nObj = {},
pice;
if (arrK.length === 0) {
localStorage.setItem(key, JSON.stringify(value));
return true;
}
pice = nObj;
for (k in arrK) {
pice[arrK[k]] = value;
pice = pice[arrK[k]];
}
var obj1 = this.get(first),
obj3 = {};
for (var k in obj1) { obj3[k] = obj1[k]; }
for (var k in nObj) { obj3[k] = nObj[k]; }
localStorage.setItem(first, JSON.stringify(obj3));
return true;
};
this.remove = function (key) {
var arrK = key.split('.'),
last = arrK.pop();
if (arrK.length === 0) {
localStorage.removeItem(key);
return true;
}
var obj = this.get(arrK.join('.'));
delete obj[last];
this.set(arrK.join('.'), obj);
return true;
};
this.destroy = function () {
localStorage.clear();
};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment