Local storage is supported by almost all of browsers these days, that makes it very easy to integrate local storage into the Ionic app. As usual, we can access it this way:
window.localStorage
Practically, to add, update or remove an item, we do this:
window.localStorage.setItem( ‘awesome-key’, ‘awesome-value’ );
window.localStorage.getItem( ‘awesome-key’ );
That’s good enough for simple data structure. When data structure gets more complicated, I mean JSON, then it’s gonna be something like this:
var appData = { name: ‘Awesome App’, version: ‘1.0.0’, description: ‘My first awesome app’ }; /* LATER ON */ // save it window.localStorage.setItem( ‘app-name’, JSON.stringify(appData)); // retrieve it var appData = JSON.parse( window.localStorage.getItem( ‘app-name’ ));
Basically, it is fine, but keep dealing with JSON.stringify() and JSON.parse() is very very very annoying and inconvenient.
Luckily, there has an Angular module that helps dealing with this, ngStorage. Since Ionic is based on Angular, we can use it in the application freely. Let’s use it to create a very simple Ionic application, a simple anything app.
Create a new blank Ionic project.
$ ionic start AnythingApp blank
Check whether project is working properly.
$ cd AnythingApp $ ionic serve
View in browser to see whether it works fine or not. It is a good habit to always verify a good-working initialized project to start with. If any error occurs at this step, you might wanna to re-create project again.
Next step is to install ngStorage as I mentioned above.
$ bower install ngstorage
According to the pre-configuration in .bowerrc, the library is installed at www/lib directory. Okay, we need to include this library into the app, by adding a line in the main www/index.html file.
<! — ionic/angularjs js →<! — add more libraries →<! — cordova script (this will be a 404 during development) →
Add you notice, I add the library right after adding the ionic.bundle.js library, that is the appropriate place to add more libraries into Ionic project.
To use the service, as mentioned in the ngStorage usage guide, we need to inject ngStorage module and the appropriate service when we need.
Next, let’s draft the basic UI for the main view:
Anything App
{{thing}}
Okay, the template also does mention the method to add new thing model to the app, and display it on the list below. We will work on this.
To separate concerns on controller, we will create a factory to handle add, remove data from local storage, where ngStorage module is in use.
Inject to main module at first hand,
// Inject ngStorage angular.module(‘starter’, [‘ionic’, ‘ngStorage’]) and then create the factory, // create a new factory .factory (‘StorageService’, function ($localStorage) { var _getAll = function () { return $localStorage.things; }; var _add = function (thing) { $localStorage.things.push(thing); } var _remove = function (thing) { $localStorage.things.splice($localStorage.things.indexOf(thing), 1); } return { getAll: _getAll, add: _add, remove: _remove }; })
You might wonder, what that $localStorage.things is about. Yay, that’s the cool thing ngStorage provides, we can use the Javascript dot-notation to access the object, which helps us to avoid writing the basic getItem, setItem.
Since, we keep every entry in local storage, we use a single key to keep them as an array. Hence, push() is applied for $localStorage.things.
Following step is to create the controller, which is MainCtrl as we specified earlier in the view.
// controller
.controller( ‘MainCtrl’, function ($scope, StorageService) { $scope.things = StorageService.getAll(); $scope.add = function (newThing) { StorageService.add(newThing); }; $scope.remove = function (thing) { StorageService.remove(thing); }; })
Almost done, you can try on browser and see what happens when you try to add a new entry, you’ll get an error…
TypeError: Cannot read property ‘push’ of undefined at Object._add [as add] (http://localhost:8100/js/app.js:16:25) at Scope.$scope.add (http://localhost:8100/js/app.js:35:20) at fn (eval at (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21972:15), :4:279) at http://localhost:8100/lib/ionic/js/ionic.bundle.js:57514:9 at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24673:28) at Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24772:23) at HTMLButtonElement. (http://localhost:8100/lib/ionic/js/ionic.bundle.js:57513:13) at HTMLButtonElement.eventHandler (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12098:21) at triggerMouseEvent (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2865:7) at tapClick (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2854:3)
It happens because we didn’t initialize the key to be used and be watched by $localStorage. Fixing it by initializing the default value for the keys we want to use in the app. Add the following line at beginning of the factory,
$localStorage = $localStorage.$default({ things: [] });
That’s it for the use of ngStorage. Actually, there are more methods provided by ngStorage, but I guess you will find it very interesting when discovering something useful about ngStorage. Be sure to follow the guide in the ngStorage usage section.
The full source code for this demo: https://github.com/petehouston/ionic-anything-app
Check out if you need a reference or have any trouble.