AngularJS : Use Local Storage(封装为服务)

AngularJS Service:Using window.localStorage directly is just fine, but having to set and parse Strings gets tiresome after a while. Use this simple AngularJS service for setting and retrieving strings or objects easily:

angular.module('ionic.utils', [])
.factory('$localstorage', ['$window', function ($window) {
    return {
        set: function (key, value) {
            $window.localStorage[key] = value;
        },
        get: function (key, defaultValue) {
            return $window.localStorage[key] || defaultValue;
        },
        setObject: function (key, value) {
            $window.localStorage[key] = JSON.stringify(value);
        },
        getObject: function (key) {
            return JSON.parse($window.localStorage[key] || '{}');
        },
        clear: function (key) {
            return $window.localStorage.removeItem(key);
        }
    }
}]);

And to use this service, just inject the $localstorage service into a controller or run function:

angular.module('app', ['ionic', 'ionic.utils'])

.run(function($localstorage) {

  $localstorage.set('name', 'Max');
  console.log($localstorage.get('name'));
  $localstorage.setObject('post', {
    name: 'Thoughts',
    text: 'Today was a good day'
  });

  var post = $localstorage.getObject('post');
  console.log(post);
});

你可能感兴趣的:(AngularJS : Use Local Storage(封装为服务))