ionic framework & Sqlite & ngCordova เป็นการใช้งานฐานข้อมูล sqlite ที่เป็นฐานข้อมูลบน smart phone ที่นิยมใช้กันใน ionic สามารถใช้ ngCordova ในการ install plugin Sqlite เพื่อใช้งานได้ทันทีดังนี้

  1. สร้างโปรเจ็คใหม่ด้วย command prompt
    ionic start sqlapp blank
    cd sqlapp
  2. ไปที่ folder sqlapp และ open with atom (text editor)
  3. ไปที่ไฟล์ config.xml แก้ไข name กับ widget id
    sqlapp1
  4. ใช้ bower install ngcordova
    bower install -g ngCordova

    หลังจากนั้นให้เปิดไฟล์ index.html และนำ script ng-cordova.js ไปวางไว้ก่อน cordova.js

    หลังจากนั้นให้เปิดไฟล์ app.js และเพิ่ม ngCordova ในส่วนของ angular.module()

    angular.module('starter', ['ionic','ngCordova'])
  5. ลง plugin Sqlite
    cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storage.git

     

  6. เปิดไฟล์ app.js กำหนด var db = null;  ไว้ด้านบนสุด
  7. ในส่วนของไฟล์ app.js ในส่วนของ $ionicPlatform.ready จะให้สร้าง db และสร้าง table ขึ้นมา
    .run(function($ionicPlatform, $cordovaSQLite) {
        $ionicPlatform.ready(function() {
          try {
            db = $cordovaSQLite.openDB({
              name: "my.db",
              location: 'default'
            });
            $cordovaSQLite.execute(db,
              "CREATE TABLE IF NOT EXISTS translog " +
              "(id integer primary key, action text, " +
              "amount integer)"
            );
          } catch (e) {
            alert(e);
          } finally {
    
          }
    
          if (window.cordova && window.cordova.plugins.Keyboard) {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    
            // Don't remove this line unless you know what you are doing. It stops the viewport
            // from snapping when text inputs are focused. Ionic handles this internally for
            // a much nicer keyboard experience.
            cordova.plugins.Keyboard.disableScroll(true);
          }
          if (window.StatusBar) {
            StatusBar.styleDefault();
          }
        });
      }) 
    
    

     

  8. ที่ command prompt สั่ง ionic platform add android
  9. และใช้คำสั่ง ionic run android
  10. พิมพ์คำสั่ง monitor ใน command prompt เพื่อเปิด android monitor
  11. พิมพ์คำสั่ง ionic run android หรือใช้คำสั่ง ionic emulate android
  12. เราสามารถเข้าดู app ของเราใน android monitor ได้จากภาพ และให้เลือก save db ลงมาเพื่อดูว่ามีข้อมูลอะไรบ้าง
    sqlapp2
  13. แก้ไขไฟล์ app.js
    // Ionic Starter App
    
    // angular.module is a global place for creating, registering and retrieving Angular modules
    // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
    // the 2nd parameter is an array of 'requires'
    var db = null;
    angular.module('starter', ['ionic', 'ngCordova'])
    
    .run(function($ionicPlatform, $cordovaSQLite) {
        $ionicPlatform.ready(function() {
          try {
            db = $cordovaSQLite.openDB({
              name: "my.db",
              location: 'default'
            });
            $cordovaSQLite.execute(db,
              "CREATE TABLE IF NOT EXISTS translog " +
              "(id integer primary key, action text, " +
              "amount integer)"
            );
          } catch (e) {
            alert(e);
          } finally {
    
          }
    
          if (window.cordova && window.cordova.plugins.Keyboard) {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    
            // Don't remove this line unless you know what you are doing. It stops the viewport
            // from snapping when text inputs are focused. Ionic handles this internally for
            // a much nicer keyboard experience.
            cordova.plugins.Keyboard.disableScroll(true);
          }
          if (window.StatusBar) {
            StatusBar.styleDefault();
          }
        });
      })
      //*****************COUNT DATA****************
      .controller('MyCon', function($scope, $ionicPlatform, $cordovaSQLite,$interval) {
    
    
        $scope.ShowCount = function() {
          /* SELECT COMMAND */
          $cordovaSQLite.execute(db,
            "SELECT count(*) as totaldata FROM translog"
          ).then(
            function(res) {
              if (res.rows.length > 0) {
                alert("have : " + res.rows.item(0).totaldata + " record.");
              }
            },
            function(error) {
              alert(error);
            }
          );
    
        }
    
        //*****************GET ALL DATA****************
        $scope.ShowAllData = function() {
          /* SELECT COMMAND */
          $scope.logs = [];
          $cordovaSQLite.execute(db,
            "SELECT * FROM translog ORDER BY id DESC"
          ).then(
            function(res) {
              if (res.rows.length > 0) {
                for (var i = 0; i < res.rows.length; i++) {
                  $scope.logs.push({
                    id: res.rows.item(i).id,
                    action: res.rows.item(i).action,
                    amount: res.rows.item(i).amount
                  });
                }
              }
            },
            function(error) {
              alert(error);
            }
          );
    
        }
    
    
    
        //*****************INSERT DATA****************
        $scope.add = function(action, amount) {
    
          try {
            if (action == 'expense') {
              amount = amount * -1;
            } else {
              amount = amount * 1;
            }
    
            if (amount != 0) {
              $cordovaSQLite.execute(db,
                "INSERT INTO translog (action, amount) VALUES(?,?)", [action, amount]
              );
            }
            alert("Inserted.");
            $scope.ShowAllData();
          } catch (e) {
            alert(e);
          } finally {
    
          }
    
    
    
    
    
    
    
    
          //$state.go('summary');
    
        };
    
        //*****************DELETE DATA****************
        $scope.delete = function(id) {
    
          try {
    
            if (id != '') {
              $cordovaSQLite.execute(db,
                "DELETE FROM translog WHERE id=?", [id]
              );
            }
            alert("Deleted.");
            $scope.ShowAllData();
          } catch (e) {
            alert(e);
          } finally {
    
          }
        };
    
    //$scope.ShowAllData();
    
    $interval($scope.ShowAllData, 2000,1);
    
    
    
    
    
      })
    

     

  14. index.html
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
    
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
    
        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
        <link href="css/ionic.app.css" rel="stylesheet">
        -->
    
        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.js"></script>
    
        <!-- cordova script (this will be a 404 during development) -->
        <script src="lib/ngCordova/dist/ng-cordova.js"></script>
        <script src="cordova.js"></script>
    
        <!-- your app's js -->
        <script src="js/app.js"></script>
      </head>
      <body ng-app="starter">
    
        <ion-pane ng-controller="MyCon">
          <ion-header-bar class="bar-stable">
            <h1 class="title">Ionic Blank Starter</h1>
          </ion-header-bar>
          <ion-content >
    
    
    
            <div class="list">
              <a href="#" class="item item-icon-left" ng-repeat="log in logs">
                  <h2>{{log.amount}}</h2>
                  <p>{{log.action}}</p>
                  <button ng-click="delete(log.id)" class="button button-block button-assertive">
                     delete
                  </button>
              </a>
          </div>
    
            <button ng-click="ShowCount()"> Show count</button>
              <button ng-click="ShowAllData()"> Show all data</button>
    
         <hr/>
         <div class="list">
                   <label class="item item-input">
                       <span class="input-label">Insert Amount</span>
                       <input type="number" ng-model="amount">
                   </label>
               </div>
    
               <div class="row">
                   <div class="col col-50">
                       <button ng-click="add('income', amount)" class="button button-large button-block button-balanced">
                           Income :)
                       </button>
                   </div>
                   <div class="col col-50">
                       <button ng-click="add('expense', amount)" class="button button-large button-block button-assertive">
                           Expense :(
                       </button>
                   </div>
               </div>
    
          </ion-content>
        </ion-pane>
      </body>
    </html>
    

     

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.