I have created a module/factory/directive for AngularJS which allows to save user input to localStorage and restore it if needed.
Although it works quite good, I am sure that I could improve its code base and am looking for advice to do so.
It can be found on github: https://github.com/sprottenwels/saintAnthony.js
Code :
;var saintAnthony = angular.module('saintAnthony',[]);
saintAnthony.directive('savior',function(blackbox){
return{
restrict: 'A',
scope: true,
link: function(scope,element,attrs){
var elementData = {};
var _getElementData = function(el){
var data = {};
var dotIndex = 0;
el = el.isString ? el : el.toString();
dotIndex = el.indexOf('.');
data.container = attrs.savior !== "" ? attrs.savior : false;
data.index = attrs.saviorindex !== undefined ? parseInt(attrs.saviorindex) : 0 ;
data.mainGroup = dotIndex !== -1 ? el.substr(0,dotIndex) : el;
data.key = el.substr(dotIndex +1,el.length);
data.value = element[0].value;
return data;
};
scope.saveSingleElement = function(){
var obj = {};
if (!blackbox.hasGroup(elementData.mainGroup)){
blackbox.addGroup(elementData.mainGroup);
}
obj[elementData.key] = elementData.value;
blackbox.updateGroup(elementData.mainGroup,obj);
};
scope.saveRepeatedElement = function(){
var obj = {};
if (!blackbox.hasGroup(elementData.container)){
blackbox.addGroup(elementData.container,true);
}
obj[elementData.key] = elementData.value;
blackbox.updateRepeatGroup(elementData.container,obj,elementData.index);
console.dir(blackbox.groups);
};
element.bind('input',function(){
elementData = _getElementData(attrs.ngModel);
scope.$apply(function(){
if(!elementData.container){scope.saveSingleElement();}
else{scope.saveRepeatedElement();}
});
});
}
}
});