Search code examples
javascriptangularjssession-storage

Best way to use sessionStorage in angular


I'm pretty new to AngularJS and I try to implement a litte Ionic App as clean as possible.

My app contains a controller for login which store the logged user in the $rootScope but I've read that using $rootScope isn't a good practices to share variables between controllers.

So I would like to use sessionStorage and localStorage but I wonder what are the best practices about it:

  • Should my ServiceLogin service write directly in storage or send data to controller which become the only who can write in storage?

  • Can/Should I use sessionStorage variable directly in html between {{ }} tags?


Solution

  • Well, the answer is it depends... It depends on the size and scope of your project and the "tidy" you want to be with your code. A simple test project just for experimenting is not the same as a big LOB application with lot of moving parts.

    Anyway, to be "angularish" you should take the first path you've said, that is, making a service that saves data to localStorage and inject it and call it on the controllers/components that need this feature. There are some modules programmed out there that also have fallback to cookie storage or others, but I find this isn't necessary at all, since local/session storage is suported for quite long on the major browsers, even mobile ones. See this.

    Reading your second option just makes my eyes sting... and won't work (making a call to window.getItem(...) from inside {{}}), at least until they release 1.6 version on wich they've removed the parser's sandbox. Anyway it's a bad practice and you should avoid it.