Need help using localstorage please


#1

I am following the example on this page http://learn.ionicframework.com/formulas/localstorage/

I put (copy/pasted) the following into the services.js file:

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] || '{}');
      }
    }
  }]);

And (copy/pasted) the following into my controllers.js file:

var app = angular.module('myapp.controllers', ['ionic.utils'])

app.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);
  });

But I get the following error:

Uncaught Error: [$injector:unpr] Unknown provider: $localstorageProvider <- $localstorage
http://errors.angularjs.org/1.2.17/$injector/unpr?p0=%24localstorageProvider%20%3C-%20%24localstorage 

I probably don’t have things in the right place. What am I doing wrong?

Thanks!


#2

Your factory name is ‘localstorage’ whereas the factory which you have injected is $localstorage hence the error. Just rename your factory to $localstorage and it should work


#3

That was it. Thank you sir.


#4

No worries :smiley: happy learning