美文网首页
AngularJS : Use Local Storage(封装

AngularJS : Use Local Storage(封装

作者: 没有故事的我 | 来源:发表于2017-05-15 16:16 被阅读0次

    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(封装

          本文链接:https://www.haomeiwen.com/subject/hyuhxxtx.html