Storing data in Ionic Framework and OnsenUI

Written by on April 9, 2015

Storing data in Ionic Framework and OnsenUI

Walkthrough

The ngStorage is AngularJS based module that makes Web Storage (LocalStorage and SessionStorage) working in the Angular Way.

This solution differs slightly from the last one.

Before we can do anything we need to initialize ngStorage module and include it into application HomeCtrl controller:

var nameApp = angular.module('starter', ['ionic','ngStorage']);
nameApp.controller('HomeCtrl', function($scope, $localStorage) {

This is how you can read, set and delete data using ngStorage:

// Read
$scope.authorization.username = $localStorage.username;
// Set
$localStorage.username =  $scope.authorization.username;
// Delete (Remove)
delete $localStorage.username;

Unlike pure vanilla approach, this one has one great benefit. You can store, read, and delete objects, without converting them to string data.

// An object
$scope.authorization = {
  username: '',
  password : ''    
};  

//Store an object
$scope.storeObject = function() { 
  if(typeof(Storage) != "undefined") {

      $localStorage.authorization =  $scope.authorization;

      alert("Data stored!");
  } else {
      alert("LocalStorage not supported!"); 
  }
}; 

//Read an object
if($localStorage.authorization !== undefined) {
  $scope.authorization = $localStorage.authorization;        
}

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="http://example.gajotres.net/include/ngStorage/ngStorage.min.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 ngStorage 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>
        
        <button class="button button-full button-positive" ng-click="storeObject()">
          Authorize - Save an object
        </button>

        <button class="button button-full button-positive" ng-click="remove()">
          Remove Data from Local Storage
        </button>        
   
      </ion-content>
      
    </ion-view>
  </script>   

</body>
 
</html>

JavaScript:

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

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


nameApp.controller('HomeCtrl', function($scope, $localStorage) {

  $scope.authorization = {
    username: '',
    password : ''    
  };  

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

      if($localStorage.authorization !== undefined) {
        
        console.log($localStorage.authorization);  
        $scope.authorization = $localStorage.authorization;
        
      } else if($localStorage.username !== undefined && 
                $localStorage.password !== undefined) {
            
        $scope.authorization.username = $localStorage.username;
        $scope.authorization.password = $localStorage.password;
                  
      }       
    
  } else {  
      alert("LocalStorage not supported!");
  }  

  $scope.signIn = function() {
    if(typeof(Storage) != "undefined") {
        $localStorage.username =  $scope.authorization.username;
        $localStorage.password =  $scope.authorization.password; 
        
        alert("Data stored!");
    } else {
        alert("LocalStorage not supported!");
    }
  }; 

  $scope.storeObject = function() { 
    if(typeof(Storage) != "undefined") {

        $localStorage.authorization =  $scope.authorization;
        console.log($scope.authorization);  

        alert("Data stored!");
    } else {
        alert("LocalStorage not supported!"); 
    }
  }; 

  $scope.remove = function() {   
    delete $localStorage.username; 
    delete $localStorage.password;
    delete $localStorage.authorization; 
    
    alert("Data removed!");    
  }; 
  
});

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



Categories

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

Leave a Reply