Sunday, February 16, 2014

Localstorage using AngularJS

I found a really nice demo app (and associated .js file as a service) at http://gregpike.net/demos/angular-local-storage/demo/demo.html

Unfortunately when I went to update my app recently, I noticed that my localstorage was getting clobered for some reason.

I after bringing up the debugger and stepping through, I found out that when the $watch was being called on the demo values, it was passing value as a null value. Now as to why this was happening I don't know, however to fix it I reverted from $watch to ng-change, so here's how.

(if you're literally using his page identically, then do a view page source and we'll move from there):
Here is the before:

And here is the after:
Note:
I added an ng-change attribute to the input field. Then in the controller, I added a call to update the variables we want to use, and added a function called change, inside that function I attempt to store the data (as before) and update the variable we are using for our text (as before).

If you've been having problems getting localStorage to work hopefully this will get you moving along.