Skip to content

Instantly share code, notes, and snippets.

@Virakal
Created July 31, 2013 16:28
Show Gist options
  • Save Virakal/6123628 to your computer and use it in GitHub Desktop.
Save Virakal/6123628 to your computer and use it in GitHub Desktop.
Automatically persist Angular ng-models between sessions using local storage.
/**
* Usage examples:
*
* <input type="text" ng-model="someText" persist></input>
*
* You can also specify a type to cast the value to:
* <input type="num" ng-model="aNumber" persist="int"></input>
*
* Valid types include:
*
* - bool | boolean
* - int | integer
* - object | json
*
* Note: If you change the name of the directive, you must also change the line `type = attrs.persist || 'string',` to match the new name.
*/
.directive('persist', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var model = attrs.ngModel,
key = '__scopePersist_' + model,
value = localStorage[key],
type = attrs.persist || 'string',
castValue;
if (value) {
switch (type) {
case 'bool':
case 'boolean':
castValue = 'true' === value;
break;
case 'int':
case 'integer':
castValue = parseInt(value, 10);
break;
case 'object':
case 'json':
castValue = JSON.parse(value);
break;
default:
castValue = value;
}
scope[model] = castValue;
}
scope.$watch(model, function (value) {
localStorage[key] = value;
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment