How To Use LocalStorage In AngularJS

Posted by Weston Ganger

With all apps these days local storage can be used for anything. Its awesome.

My favourite is to use the ngStorage module for both local storage and session storage.


The simple alternative is to create a small angular service to interact which works perfect too.


yourApp.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue || false;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key, defaultValue) {
      if($window.localStorage[key] != undefined){
          return JSON.parse($window.localStorage[key]);
      }else{
        return defaultValue || false;
      }
    },
    remove: function(key){
      $window.localStorage.removeItem(key);
    },
    clear: function(){
      $window.localStorage.clear();
    }
  }
}]);


Related External Links:

Article Topic:Software Development - Angular

Date:March 07, 2016

Recommended Posts

Contact

604-309-8713
info@solidfoundationwebdev.com

Send Me A Message

I would love to get in touch and talk about your next project. Feel free to send a message and I will get back to you shortly.

Get Connected