Friday, 23 October 2015

Example of SQLite in Ionic Framework

Hello,

Here i am sharing an example of SQLite in Ionic Framework.

So, following are the commands to start a project in Ionic Framework-

 ionic start IonicSqliteProject blank
cd IonicSqliteProject
ionic platform add android

The next thing we want to do is add the SQLite plugin.  This can be done by running the following command:

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git 



Download the latest release and copy ng-cordova.min.js into your www/js directory.


Then include that  ng-cordova.min.js file in your index.html file , your index.html file look like-

<!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">     
    <script src="lib/ionic/js/ionic.bundle.js"></script>     
    <script src="js/ng-cordova.min.js"></script>      
   <script src="cordova.js"></script>        
 <script src="js/app.js"></script>  
   </head>


Here i am only showing the head section of index.html file, rest will same.


One more thing must be added before we can start using ngCordova.  We need to inject it into our angular.module, that is in app.js, like the following:


angular.module('starter' , ['ionic','ngCordova'])


It’s time to start using this library.  For simplicity, we are going to do the following:
  1. Create a new table called demo
  2. Insert two people into this new table
  3. Select all the people found in our table with my last name

Before we start coding, it is very important to note that database activity can only be done when the onDeviceReady() method has fired.  With this in mind, I’m going to open the database in the modules .run() method like so:


var db = null;
var example = angular.module('starter', ['ionic', 'ngCordova'])  
  .run(function($ionicPlatform, $cordovaSQLite)  
{    
    $ionicPlatform.ready(function()  
{        
    if(window.cordova && window.cordova.plugins.Keyboard) 
{            
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);        
    }   
          if(window.StatusBar) 
{          
 StatusBar.styleDefault();        
    }       
      db = $cordovaSQLite.openDB("my.db");         
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS demo (id integer primary key, firstname text, lastname text)");     
    });   
  });


 We want to have access to the database globally so I created a variable outside of any method or controller.  To use the ngCordova functions we need to include $cordovaSQLite in the .run() method.  Finally, you can see that I’ve created a new database called my.db and a fresh table called demo.
This leaves us with a usable database ready for activity in our controllers.  Take the following for example:


example.controller("ExampleController", function($scope, $cordovaSQLite)
{    $scope.insert = function(firstname, lastname)
{       
 var query = "INSERT INTO demo (firstname, lastname) VALUES (?,?)";     
   $cordovaSQLite.execute(db, query, [firstname, lastname]).then(function(res)
{       
   console.log("INSERT ID -> " + res.insertId);     
   },
function (err)
{            console.error(err);        });  
  }    $scope.select = function(lastname)
{       
 var query = "SELECT firstname, lastname FROM demo WHERE lastname = ?";     
   $cordovaSQLite.execute(db, query, [lastname]).then(function(res) {          
  if(res.rows.length > 0)
{           
     console.log("SELECTED -> " + res.rows.item(0).firstname + " " + res.rows.item(0).lastname);         
   }
else
{                console.log("No results found");            }    
    }, function (err)
{            console.error(err);        });   
 }
});



Here i have created two very basic functions.  The insert function will add a first and last name record into the database while the select function will find records by last name.


Something to note about my controller though.  I am not doing these database calls from inside an onDeviceReady() function.  Had these functions been fired when the controller loads, they probably would have failed.  Since I am basing the database activity off button clicks, it is probably safe to assume the device and database is ready for use.



Thanks...

Monday, 28 September 2015

Implement Google Maps Using Ionic Framework

Hi,

Here is a way by which we can implement Google Maps in Ionic framework

Run the following command for a blank Ionic project-

ionic start Map blank
cd Map
ionic platform add android

Since we are using maps, it is probably a good idea to add geolocation functionality to your application.  You can add the Apache Cordova Geolocation API by running the following command:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git


We are going to be using the Google Maps JavaScript SDK, which requires us to have an API key for use in our application.  Go into your Google API Console and register a new Google Maps application.

When you have Google API key, crack open your www/index.html file because we need to add the JavaScript library to our project.

<!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>
      <ion-header-bar class="bar-stable">
          <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content >
       
      </ion-content>
  </ion-pane>
  <script src="http://maps.googleapis.com/maps/api/js?key=Your_API_key&sensor=true"></script>
  </body>
</html>

Please note that the Google Maps JavaScript library cannot be downloaded, so there will always be a small delay during the initial setup when you launch your application.



Now that the SDK is included we need to add some CSS for displaying it on the screen.  Open your www/css/style.css file and add the following code:

.scroll {
    height: 100%;
}
#map {
    width: 100%;
    height: 100%;
}

Open your www/app.js file because we want to add a controller that handles the Google Map.

var Map = angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
Map.controller('MapController', function($scope, $ionicLoading) {
    google.maps.event.addDomListener(window, 'load', function() {
        var myLatlng = new google.maps.LatLng(37.3000, -120.4833);
        var mapOptions = {
            center: myLatlng,
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
        navigator.geolocation.getCurrentPosition(function(pos) {
            map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
            var myLocation = new google.maps.Marker({
                position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
                map: map,
                title: "My Location"
            });
        });
        $scope.map = map;
    });
});


  We need to add some code to our www/index.html file for containing the map.


 <ion-content ng-controller="MapController">
          <div id="map" data-tap-disabled="true"></div>
      </ion-content>

Thanks. 

Friday, 25 September 2015

Using camera in ionic project

Hi,

Here is a cordova plugin for open a camera in ionic project-

Run the following command-

cordova plugin add org.apache.cordova.camera 

Then your main.html file look like-

<ion-view view-title="Profile">
    <ion-content>
            <div class="align-center">
     
                    <div class="user_img" ng-click="capture()">
                      Click here
                    </div>
</div> 
    </ion-content>
</ion-view>

And controller.js file look like-

myapp.controller('ProfileCtrl', function ($scope, $cordovaCamera) {
    var options = {
        quality: 50,
       destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        targetWidth: 150,
        targetHeight: 150,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false,
        correctOrientation: true
    };
    $scope.capture = function () {
      $cordovaCamera.getPicture(options).then(function (imageData) {
            var image = document.getElementById('myImage');
            console.log("image",image)
            //image.src = "data:image/jpeg;base64," + imageData;
        }, function (err) {
            console.log("error",JSON.stringify(err))
        });
    }
});
 

Thanks


Friday, 18 September 2015

Floating point number to integer number in angularjs

Hi,

Here is a way in angularjs by which you can change a floating point number to integer -

In your index.html

       <script>
angular.module('Example', [])
.controller('ExampleController',[$scope',function($scope){
$scope.val = 123.455;
}])

               
                  </script>



<div ng-controller="ExampleController">
<label>Enter number:<input ng-model='val'></label>
<br>
<br>
number in floating point format:<span id='number-default'>
{{val | number}}
</span>
<br>
number in integer format:<span>
{{val | number:0}}
</span>
<br>
Negative number:<span>
{{-val | number:4}}
</span>
<br>
</div>


Thanks 

Friday, 11 September 2015

Plugins to be required to run an ionic app

Hi,

Following are the plugins, which are required to run an ionic app in mobile-

1)Plugin for email composer-

cordova plugin add https://github.com/jcjee/email-composer.git

2)Plugin for date picker-

cordova plugin add cordova-plugin-datepicker


3)Plugin for in app browser-

cordova plugin add cordova-plugin-inappbrowser


4) Plugin for splash screen-

cordova plugin add cordova-plugin-splashscreen

5)Plugin for status bar-

cordova plugin add cordova-plugin-statusbar

6)Plugin for white-list -

ionic plugin add https://github.com/apache/cordova-plugin-whitelist.git

7)Plugin for Keyboard-

cordova plugin add com.ionic.keyboard

8)Plugin for console-

cordova plugin add org.apache.cordova.console

9)Plugin for device-

cordova plugin add org.apache.cordova.device


Thanks


Friday, 4 September 2015

Ionic modal


                       In Ionic, modals are provided by the $ionicModal  directive.  Ionic’s modal allows creation from either a template string or a URL. 
Here in this example we are using a URL.

Modals are created with a scope. This can be used in simple examples to pass data. 

Example:-
For using the $ionicModal directive in our example following will be the code of index.html-


<ion-header-bar class="bar-energized">
<h1 class="title">
Contact Info
</h1>
<ion-content>
<div class="card" ng-controller='MainCtrl' ng-click="openModal()">
<div class="item item-divider">
{{contact.name}}
</div>
<div class="item item-text-wrap">
{{contact.info}}
</div>
</div>
</ion-content>


contact.html 

HTML page which we call by the $ionicModal-


<script id="contact.html" type="text/ng-template"> <div class="modal"> <ion-header-bar> <h1 class="title">Edit Contact</h1> </ion-header-bar> <ion-content> <div class="list"> <label class="item item-input"> <span class="input-label">Name</span> <input type="text" ng-model="contact.name"> </label> <label class="item item-input"> <span class="input-label">Info</span> <input type="text" ng-model="contact.info"> </label> </div> <button class="button button-full button-energized" ng-click="closeModal()">Done</button> </ion-content> </ </div></script>


Now our controller.js file look like-


app.controller('MainCtrl', function($scope, $ionicModal) { $scope.contact = { name: 'Demo', info: 'Tap anywhere on the card to open the modal' } $ionicModal.fromTemplateUrl('contact.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal }) $scope.openModal = function() { $scope.modal.show() } $scope.closeModal = function() { $scope.modal.hide(); }; $scope.$on('$destroy', function() { $scope.modal.remove(); });})

Friday, 21 August 2015

Trigger side-menu on hardware back button click in ionic

Hello,

Here i am sharing a method by which we can open side menu in side-menu ionic app by clicking the hardware back button, and it will be happened when side menu is closed, and we clicked on hardware back button than side menu will open . And if side menu is open than a pop up will be show on screen for exiting from app by clicking on hardware back button.

So we include following code in our app.js 




.run(function ($ionicPlatform,                   $cordovaStatusbar, $ionicPopup,$ionicSideMenuDelegate                   ) {     $ionicPlatform.onHardwareBackButton(function () {
            if ($ionicSideMenuDelegate.isOpen()) {                // your check here                $ionicPopup.confirm({                    template:                        '<div style=" color:#255B73; text-align: center; font-size:18px;">Exit the app?</div>',                    buttons: [                        { text: 'Cancel' },                        {                            text: '<b>Exit</b>',                            type: 'button-positive',                            onTap: function () {                                return true;                            }                        }                    ]                }).then(function (res) {                    if (res) {                        navigator.app.exitApp();                    }                })            } else {                $ionicSideMenuDelegate.toggleLeft()            }
        });
})



Thanks....