Storing data in Ionic Framework and OnsenUI

Written by on April 9, 2015

Storing data in Ionic Framework and OnsenUI

Last few weeks I’ve been working on a series covering Ionic Framework and OnsenUI. All of that came to halt on this topic. Both frameworks can use same methods of data storing, so there’s no point in writing separate articles.

When working with hybrid mobile applications being able to persist local data is crucial. A some time ago it was done with cookies, now we can use a Web Storage. Unlike cookies, these technologies can store a large amount of data, and it’s available only when you request it. This data holds name/value pairs, and websites (or applications) can only access their private data.

Do not use these techniques to store important data (like passwords, API keys, etc.)

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Table of Contents

[spoiler title=” Click here if you want to see other OnsenUI tutorials.”]

[/spoiler]

[spoiler title=” Click here if you want to see other Ionic tutorials, or articles about Ionic themes, templates, plugins …”]

Tutorials

Other Resources (themes, templates, plugins, Cordova plugins, starter apps)

Cordova Plugin Tutorials


[/spoiler]

Intro

I will demonstrate several solutions, if possible I will also include working examples.

The first solution depends on direct LocalStorage access:

window.localStorage.setItem("key",value);

In this case, we set the key named key holding some value. You may also heard of a slightly different syntax:

window.localStorage['key'] = value;

This approach also works, but I would like to advise you against it, some browsers don’t support this way of access.

The second solution still uses LocalStorage approach, but this time it’s wrapped into AngularJS module:

angular.module('app', [
    'ngStorage'
]).controller('Ctrl', function(
    $scope,
    $localStorage,
    $sessionStorage
){});

Both solutions also have a significant downside; you can store maximum 5MB of data.

Solution 1 – Vanilla LocalStorage Access

Demo

Embedded working example

Ionic Framework LocalStorage Example

Walkthrough

There’s nothing special about this example, only part of code worth mentioning is this one:

$scope.signIn = function() {
  if(typeof(Storage) != "undefined") {
      window.localStorage.setItem("username", $scope.authorization.username);
      window.localStorage.setItem("password", $scope.authorization.password);
        
      alert("Data is stored, reload this page to retrieve it back!");
  } else {
      alert("LocalStorage not supported!");
  }
};    
  
$scope.remove = function() { 
  window.localStorage.removeItem("username");
  window.localStorage.removeItem("password");
};  

While not necessary, it is a good practice to check if a browser supports Local Storage before you start doing anything with it:

if(typeof(Storage) != "undefined") {

When you restart this example, Controller will prefill both input fields so make sure you actually write something before you click Authorize button. You can also remove stored data using removeItem function:

  window.localStorage.removeItem("username");
  window.localStorage.removeItem("password");

HTML:

<html ng-app="starter">
 
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
  <title>Ionic Framework Example</title>
  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet"/>
  <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
  <script src="script.js"></script>
</head>
 
<body>
  
  <ion-nav-bar class="bar-positive"></ion-nav-bar>
  
  <ion-nav-view></ion-nav-view>
  
  <script id="home.html" type="text/ng-template">
    <ion-view view-title="Ionic Framework LocalStorage Example">  
    
      <ion-content class="padding">

        <h2 style="text-align:center;">1. Enter Username and Password data</h2>
        <h2 style="text-align:center;">2. Press Authorize button</h2>
        <h2 style="text-align:center;">3. Reload this page</h2><br/>

        <div class="list">
          <label class="item item-input">
            <span class="input-label">Username</span>
            <input type="text" ng-model="authorization.username">
          </label>
          <label class="item item-input">
            <span class="input-label">Password</span>
            <input type="password" ng-model="authorization.password">
          </label>
        </div>

        <button class="button button-full button-positive" ng-click="signIn()">
          Authorize
        </button>
   
      </ion-content>
      
    </ion-view>
  </script>   

</body>
 
</html>

JavaScript:

var nameApp = angular.module('starter', ['ionic']);

nameApp.config(function($stateProvider, $urlRouterProvider) {
 
  $stateProvider
    .state('home', {
      url: '/',
      templateUrl: 'home.html',
      controller: 'HomeCtrl'
    });
  $urlRouterProvider.otherwise("/");
 
});


nameApp.controller('HomeCtrl', function($scope) {
  
  
  $scope.authorization = {
    username: '',
    password : ''    
  };  
  
  if(typeof(Storage) != "undefined") {
      $scope.authorization.username = window.localStorage.getItem("username");
      $scope.authorization.password = window.localStorage.getItem("password");
  } else {
      alert("LocalStorage not supported!");
  }  
  
  $scope.signIn = function() {
    if(typeof(Storage) != "undefined") {
        window.localStorage.setItem("username", $scope.authorization.username);
        window.localStorage.setItem("password", $scope.authorization.password);
        
        alert("Data is stored, reload this page to retrieve it back!");
    } else {
        alert("LocalStorage not supported!");
    }
  };    
  


});

Solution 2 – ngStorage

ngStorage GitHub
Demo

Embedded working example

Ionic Framework LocalStorage Example

Continue Reading

Categories

1 thought on “Storing data in Ionic Framework and OnsenUI”

Leave a Reply