Support Storage

You saw back in Chapters 17 through 19 that we can create a Web API for storing data and accessing it with web code. The same is true for mobile applications. They can connect to your Web API (running on Azure or another cloud platform). This API can then save data to a database or some other storage mechanism. You can make further API calls to retrieve the data.

Here, however, we are going to look at storing data locally on the device. We have a couple options to do so. First, we can use HTML5 Web Storage (localStorage). Alternatively, we could use a small database that is pushed to the device, such as SQLite. We are going to work with the former approach (HTML 5 Web Storage). Of course, you might consider a hybrid approach in which users can work offline (local storage) and then synch through a Web API (cloud storage). This is a popular model for many applications.

We are going to add storage support to the application created to this point. If you have not been following along, you can start with a version of the application to this point from the download for this book. This version is inside the folder CordovaIonicSample - BeforeStorage. The following walks you through adding local storage to an application:

1. Clean up the addEntry() method inside the CalculateCtrl to make it add a real item to the log. Open controllers.js and navigate to addEntry(). Change the method to mimic the code that follows.

Notice that the only difference here is that we create a real item based on the bound $scope. We then call the Log service to add the item.

$scope.addEntry = function () {
  //Add the item to the log scope.
  var item = {
    date: (new Date().toDateString()),
    data: 'Distance: ' + $scope.entry.distance +
        ', Time: ' + $scope.entry.time +
        ', Pace: ' + $scope.pace
  };

  Log.addItem(item);

  //Clear the form; show success.
  $scope.pace = '';
  $scope.entry = { distance: '', time: '' };
  document.getElementById('paceDisplay').style.display = 'none';
  $scope.showAlert();

};

2. Modify the services.js file to work with HTML Web Storage. Listing 25.8 shows an example with line numbers for reference. The following walks through this code:

Line 07—We set a key to be used by this application for storing and retrieving data from the HTML Web Storage.

Line 10—The loadFromStorage method uses Angular to load JSON into an array. The data is loaded from the localStorage.getItem method of $window (passed into the service by Angular).

Line 15—The saveToStorage method uses $window.localStorage to save the data as JSON (angular.toJson).

Line 23—The Log.all() method simply calls loadFromStorage to return all items from local storage.

Line 28—The Log.addItem() method takes an item as a parameter. It then loads the data from local storage, adds an item, and saves the data back.

Line 35—The Log.clear() method loads the data from storage, removes all items in the array (using JavaScript splice) and then saves the empty results back to local storage.

LISTING 25.8 The Log Service Code Inside the services.js File


01  angular.module('starter.services', [])
02
03  .factory('Log', ["$window", function ($window) {
04
05    //Init objects and methods.
06    var log = [];
07    var storageKey = "appMyRunMyRide";
08
09    //Load from local storage.
10    var loadFromStorage = function () {
11      return angular.fromJson($window.localStorage.getItem(storageKey)) || [];
12    };
13
14    //Save all to local storage.
15    var saveToStorage = function (items) {
16      $window.localStorage.setItem(storageKey, angular.toJson(items));
17    }
18
19    //Define services.
20    return {
21
22      //Get all items from storage.
23      all: function() {
24        return loadFromStorage();
25      },
26
27      //Add an item to storage and save.
28      addItem: function (item) {
29        var items = loadFromStorage();
30        items.push(item);
31        saveToStorage(items);
32      },
33
34      //Delete the local storage and save.
35      clear: function () {
36        var items = loadFromStorage();
37        items.splice(0, items.length);
38        saveToStorage(items);
39      }
40    };
41  }]);


3. IMPORTANT: By default, Ionic caches views in your application to help make performance better. However, this can often cause issues such as adding a new item to the Log, navigating to the log, and not seeing the item. Thankfully, you can control the Ionic cache inside the AngularUI router code found in app.js. Edit the tab.log state call as follows in order to add cache: false to the parameters list.

.state('tab.log', {
  cache: false,
  url: '/log',
  views: {
    'tab-log': {
      templateUrl: 'templates/tab-log.html',
      controller: 'LogCtrl',
    }
  }
})

You can again run the application to see the changes. You should now have a persistent log of items. Figure 25.20 shows the app after some actual items have been logged. You should be able to close the app and return to it and find that your logged items are still stored locally.

Image

FIGURE 25.20 The sample app storing and retrieving data from the HTML Web Storage (local storage).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset