Showing posts with label Ionic Framework. Show all posts
Showing posts with label Ionic Framework. Show all posts

Ionic Framework - Camera Image Uploads and Base64 Strings

Ionic Framework - Camera Image Uploads and Base64 Strings


Hi Today Discussed Ionic Framework - Camera Image Uploads and Base64 Strings menas Ionic Framework Build Mobile Application Framework. Previously more discussed Ionic Framework Today Camera Take Picture image uploads and Base64 strings. This Task discussed  more details followed. 

Ionic Framework - Camera Image Uploads and Base64 Strings
Ionic Framework - Camera Image Uploads and Base64 Strings

First Install Image Resizer Plugin

cordova plugin add https://github.com/timkalinowski/PhoneGap-Image-Resizer

Install the Actionsheet Plugin

cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-actionsheet

Install the Camera Plugin

cordova plugin add cordova-plugin-camera

The Code

We are using the camera plugin here, but I did not use Ionic Framework with ngCordova – Camera here for the sake of simplicity, I suspect you will get the same behavior if you are using the ngCordova – Camera module to access the camera.

getPicture: function (options) {
    var q = $q.defer();
 
    navigator.camera.getPicture(function (result) {
        // Do any magic you need
        q.resolve(result);
    }, function (err) {
        q.reject(err);
    }, options);
 
    return q.promise;
},resizeImage: function (img_path) {
    var q = $q.defer();
    window.imageResizer.resizeImage(function (success_resp) {
        console.log('success, img re-size: ' + JSON.stringify(success_resp));
        q.resolve(success_resp);
    }, function (fail_resp) {
        console.log('fail, img re-size: ' + JSON.stringify(fail_resp));
        q.reject(fail_resp);
    }, img_path, 200, 0, {
        imageDataType: ImageResizer.IMAGE_DATA_TYPE_URL,
        resizeType: ImageResizer.RESIZE_TYPE_MIN_PIXEL,
        pixelDensity: true,
        storeImage: false,
        photoAlbum: false,
        format: 'jpg'
    });
 
    return q.promise;
},
toBase64Image: function (img_path) {
    var q = $q.defer();
    window.imageResizer.resizeImage(function (success_resp) {
        console.log('success, img toBase64Image: ' + JSON.stringify(success_resp));
        q.resolve(success_resp);
    }, function (fail_resp) {
        console.log('fail, img toBase64Image: ' + JSON.stringify(fail_resp));
        q.reject(fail_resp);
    }, img_path, 1, 1, {
        imageDataType: ImageResizer.IMAGE_DATA_TYPE_URL,
        resizeType: ImageResizer.RESIZE_TYPE_FACTOR,
        format: 'jpg'
    });
 
    return q.promise;
}

Supporting File Uploads To Parse

/********************************************************
 *                                                      *
 * @param _params.photo base64 representation of photo  *
 * @param _params.caption string to go with photo       *
 ********************************************************/ 
savePhotoToParse: function (_params) {
    var ImageObject = Parse.Object.extend("ImageInfo");
 
    // create the parse file object using base64 representation of photo
    var imageFile = new Parse.File("mypic.jpg", {base64: _params.photo});
 
 
    // save the parse file object
    return imageFile.save().then(function () {
 
        _params.photo = null;
 
        // create object to hold caption and file reference
        var imageObject = new ImageObject();
 
        // set object properties
        imageObject.set("caption", _params.caption);
        imageObject.set("picture", imageFile);
 
        // save object to parse backend
        return imageObject.save();
 
    }, function (error) {
        alert("Error " + JSON.stringify(error, null, 2));
        console.log(error);
    });
 
}

Using Charts in Your Ionic Framework Mobile App

Using Charts in Your Ionic Framework Mobile App

Hi Today Discussed Ionic Framework Using charts in your Ionic Framework Mobile Appplication Highcharts and Stockcharts More attractive and pretty chart highcharts. Here Looks Like pretty chart using Ionic Framework is Follows Code.

Using Charts in Your Ionic Framework Mobile App
Using Charts in Your Ionic Framework Mobile App


Index Page

<!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 rel="stylesheet" href="css/angular-chart.css">
        <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="cordova.js"></script>
        <!-- your app's js -->
        <script src="js/Chart.min.js"></script>
        <script src="js/angular-chart.min.js"></script>
        <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>
    </body>
</html>

Module Inject
angular.module('starter', ['ionic', 'chart.js'])
Controller Page

controller("ChartController", function($scope) {
    $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
    $scope.series = ['Series A', 'Series B'];
    $scope.data = [
        [65, 59, 80, 81, 56, 55, 40],
        [28, 48, 40, 19, 86, 27, 90]
    ];
});

Html Page

 <ion-content ng-controller="ChartController">
    <div class="card">
        <div class="item item-divider">
            A line chart
        </div>
        <div class="item item-text-wrap">
            <canvas id="line" class="chart chart-line" data="data" labels="labels" legend="true" series="series" options="{showTooltips: false}"></canvas>
        </div>
    </div>
    <div class="card">
        <div class="item item-divider">
            A bar chart
        </div>
        <div class="item item-text-wrap">
            <canvas id="bar" class="chart chart-bar" data="data" labels="labels" legend="true" series="series" options="{showTooltips: false}"></canvas>
        </div>
    </div>
</ion-content>



Ionic + Braintree JS integration

Ionic + Braintree JS integration



Hi Today Discussed  Ionic Framework Braintree JS Integration. Ionic Framework.Braintree Payments drop-in into an Ionic mobile app I have them with an ionic modal view. Here follows Code.
Ionic + Braintree JS integration
Ionic + Braintree JS integration

Html Page
<ion-content ng-controller="payController">

        <div ng-show="step == 'signup'">
          <div class="list">
            <label class="item item-input"><input type="text" placeholder="First name" ng-model="customer.firstname"></label>
            <label class="item item-input"><input type="text" placeholder="Last name" ng-model="customer.lastname"></label>
            <label class="item item-input"><input type="text" placeholder="Company" ng-model="customer.company"></label>
            <label class="item item-input"><input type="text" placeholder="email" ng-model="customer.email"></label>
            <label class="item item-input"><input type="text" placeholder="phone" ng-model="customer.phone"></label>
          </div>
          <div class="padding">
            <button class="button button-block button-positive" ng-click="signup(customer)" ng-disabled="!ready">Continue</button>
          </div>
        </div>

        <div ng-show="step == 'verification'">
          <div class="list">
            <label class="item item-input">
              <input type="text" placeholder="Cardholder name" ng-model="card.cardholder">
            </label>
            <label class="item item-input">
              <input type="text" placeholder="Number" ng-model="card.number">
            </label>
            <label class="item item-input">
              <input type="text" placeholder="CVV" ng-model="card.cvv">
            </label>

            <label class="item item-input">
              <span class="input-label">Expire date</span>
              <input type="text" placeholder="mm" ng-model="card.expiration_month">
              <input type="text" placeholder="yy" ng-model="card.expiration_year">
            </label>
          </div>
          <div class="padding">
            <button class="button button-block button-positive" ng-click="saveCard(card)" ng-disabled="!ready">Save</button>
          </div>
        </div>

        <div ng-show="step == 'checkout'">
          <div class="item range">
            <span>€</span>
            <input type="range" ng-model="amount" min="0" max="100">
            <span>{{ amount }}</span>
          </div>
          <div class="padding">
            <button class="button button-block button-positive" ng-click="pay(10)" ng-disabled="!ready">Pay</button>
          </div>
        </div>

        <div ng-show="step == 'done'">
          <p>Transaction completed with transaction id: {{ transactionId }}</p>
        </div>
App.js

 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();
    }
  });
})


Services.js


angular
 .module('starter')
 .factory('braintreeService', braintreeFactory);

function braintreeFactory($http) {

 /**
  * Braintree server-side implementation
  * @type string
  */
 var Url = 'Api URL';

 return {

  getClientToken: function(customerId) {
   return $http
    .get(Url + '/Access_token' + (cus_Id ? '/' + cus_Id: ''))
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }

     throw 'Invalid response';
    });
  },

  createCustomer: function(firstName, lastName, company, email, phone, fax, website) {
   var postData = {
    customer: {
     firstName: firstName,
     lastName: lastName,
     company: company,
     email: email,
     phone: phone,
     fax: fax,
     website: website
    }
   };

   return $http
    .post(Url + '/cus', postData)
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }
    });
  },

  createPaymentMethod: function(customerId, nonce) {
   var postData = {
    paymentMethod: {
     customerId: customerId,
     paymentMethodNonce: nonce
    }
   };
   return $http
    .post(Url + '/payment_method', postData)
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }
    });
  },

  sale: function(amount, paymentMethodToken) {
   var postData = {
    transaction: {
     amount: amount,
     paymentMethodToken, paymentMethodToken
    }
   };

   return $http
    .post(Url + '/sale', postData)
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }
    });
  }

 };


};


Controller.js

angular
 .module('starter')
 .controller('payController', payController);

function payController($scope, braintreeService) {
 /**
  * Form steps
  * 1. signup - create customer
  * 2. verification - save & validate card
  * 3. checkout - charge the card
  * 4. done - displays transaction id
  */
 $scope.step = 'signup';

 /**
  * customerId in Braintree
  * reference to credit card in Braintree
  * 
  * These should be persisted for future reference
  */
 $scope.customerId = false;
 $scope.paymentMethodToken = false;
 $scope.amount = 10;

 /**
  * Bypass step forms for testing
  */
 /*$scope.customerId = '';
 $scope.step = 'checkout';
 $scope.paymentMethodToken = '';
 $scope.card = {
  cardholder: 'Michael',
  number:'4111111111111111',
  cvv: 444,
  expiration_month: 10,
  expiration_year: 18
 };*/

 /**
  * Setup Braintree client with clientToken generated on our server
  */
 $scope.ready = false;
 var braintreeClient;
 braintreeService.getClientToken().then(function(clientToken) {
  // braintree.setup(clientToken, "custom", {id: "checkout", enableCORS: true});
  braintreeClient = new braintree.api.Client({clientToken: clientToken, enableCORS: true});
  $scope.ready = true;
 });

 /**
  * Creates braintree customer
  */
 $scope.signup = function(customer) {
  braintreeService
   .createCustomer(customer.firstname, customer.lastname, customer.company, customer.email, customer.phone)
   .then(function(customerId) {
    console.log("customerId " + customerId);
    $scope.customerId = customerId;
    $scope.step = 'verification';
   });
 };

 /**
  * Save card
  */
 $scope.saveCard = function(card) {
  // console.log('tokenizing card', card);
  braintreeClient.tokenizeCard({
   number: card.number,
   cardholderName: card.cardholder,
   expirationMonth: card.expiration_month,
   expirationYear: card.expiration_year,
   cvv: card.cvv
   // billingAddress: {}
  }, function(err, nonce) {
   if (err) {
    throw err;
   }

   braintreeService
    .createPaymentMethod($scope.customerId, nonce)
    .then(function(paymentMethodToken) {
     console.log('paymentMethodToken ' + paymentMethodToken);
     $scope.paymentMethodToken = paymentMethodToken;
     $scope.step = 'checkout';
    });
  })
 };

 $scope.pay = function(amount) {
  braintreeService
   .sale(amount, $scope.paymentMethodToken)
   .then(function(transactionId) {
    $scope.step = 'done';
    $scope.transactionId = transactionId;
    console.log('transactionId ' + transactionId);
   });
 };
};



Ionic Framework Paypal Payment Gateway

Ionic Framework Paypal Payment Gateway


Today Discussed Ionic Framework Paypal payment Gateway. First  Ionic Framework Cordova Plugin. and How to get payment gateway integrated follows. 
Ionic Framework Paypal Payment Gateway
Ionic Framework Paypal Payment Gateway
IK have developed a mobile app using ionic framework and cordova. In my backend mysql. and storing data using php code. Cordova Plugin ClientID here  api keys.

 $scope.buyNow = function ()
    {
        PaypalService.initPaymentUI().then(function () { PaypalService.makePayment(50, "Total").then();       });
    }
PaypalService is implemented as 
ngular.module('starter.PaypalService', ['starter.Constants'])
.factory('PaypalService', ['$q', '$ionicPlatform','Constants', '$filter', '$timeout', function ($q, $ionicPlatform, Constants, $filter, $timeout) {



    var init_defer;
    /**
     * Service object
     * @type object
     */
    var service = {
        initPaymentUI: initPaymentUI,
        createPayment: createPayment,
        configuration: configuration,
        onPayPalMobileInit: onPayPalMobileInit,
        makePayment: makePayment
    };


    /**
     * @ngdoc method
     * @name initPaymentUI
     * @methodOf app.PaypalService
     * @description
     * Inits the payapl ui with certain envs.
     *
     *
     * @returns {object} Promise paypal ui init done
     */
    function initPaymentUI() {

        init_defer = $q.defer();
        $ionicPlatform.ready().then(function () {

            var clientIDs = {
                "PayPalEnvironmentProduction": Constants.payPalProductionId,
                "PayPalEnvironmentSandbox": Constants.payPalSandboxId
            };
            PayPalMobile.init(clientIDs, onPayPalMobileInit);
        });

        return init_defer.promise;
    }

    /**
     * @ngdoc method
     * @name createPayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Creates a paypal payment object
     *
     *
     * @returns {object} PayPalPaymentObject
     */
    function createPayment(total, name) {

        // "Sale  == >  immediate payment
        // "Auth" for payment authorization only, to be captured separately at a later time.
        // "Order" for taking an order, with authorization and capture to be done separately at a later time.
        var payment = new PayPalPayment("" + total, "INR", "" + name, "Sale");
        return payment;
    }
    /**
     * @ngdoc method
     * @name configuration
     * @methodOf app.PaypalService
     * @description
     * Helper to create a paypal configuration object
     *
     *
     * @returns {object} PayPal configuration
     */
    function configuration() {
        // for more options see `paypal-mobile-js-helper.js`
        var config = new PayPalConfiguration({merchantName: Constants.payPalShopName, merchantPrivacyPolicyURL: Constants.payPalMerchantPrivacyPolicyURL, merchantUserAgreementURL: Constants.payPalMerchantUserAgreementURL});
        return config;
    }

    function onPayPalMobileInit() {
        $ionicPlatform.ready().then(function () {
            // must be called
            // use PayPalEnvironmentNoNetwork mode to get look and feel of the flow
            PayPalMobile.prepareToRender(Constants.payPalEnv, configuration(), function () {

                $timeout(function () {
                    init_defer.resolve();
                });

            });
        });
    }
    /**
     * @ngdoc method
     * @name makePayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Performs a paypal single payment
     *
     *
     * @returns {object} Promise gets resolved on successful payment, rejected on error
     */
    function makePayment(total, name) {


        var defer = $q.defer();
        total = $filter('number')(total, 2);
        $ionicPlatform.ready().then(function () {
            PayPalMobile.renderSinglePaymentUI(createPayment(total, name), function (result) {
                $timeout(function () {
                    defer.resolve(result);
                });
            }, function (error) {
                $timeout(function () {
                    defer.reject(error);
                });
            });
        });

        return defer.promise;
    }

    return service;
}]);
Followed Step

API Backend and Integrations

Every app talks to a server or backed and Appery.io provides a complete backend for your app:

  • Database - for storing app data.
  • Server Code - for writing app logic on the server using JavaScript.
  • API Express - exposing enterprise data sources such as an SQL database or SOAP service via REST APIs. Also, build advanced services with a visual service editor.
  • Push Notifications - send Push Notifications to your users.

Ionic Framework web services loop $http json request

Ionic Framework web services loop $http json request

Ionic Framework web services loop $http json request
Web Services Loop $http json request

Today Discussed Ionic Framework web Services data looping Concepts.  Angularjs Previously discussed angularjs looping concepts same based ionic framework used. Angularjs and Ionic Framework is same concepts. Here follows this sample code in ionic framework and more information and example click here

controller('DataCtrl', function($scope, $http, data) {
  $scope.name = 'World';
  $scope.allads = [];
  $scope.data= [];

  $http.get('http://www.mysite.com/list.json').success(function(data) {
    $scope.allads = data;
    $scope.loadMore();
  });

  var counter = 0;

  $scope.loadMore = function() {
    var data = [];
    var l = $scope.data.length;
    var m = Math.min(l+10, $scope.allads.length);
    for ( var i = l; i < m; i++) {
      data.push($scope.allads[i]);
    }

    console.log('Loading more!', m);
    $scope.ads = $scope.ads.concat(data);
    $scope.$broadcast('scroll.infiniteScrollComplete');
  };

  $scope.$on('stateChangeSuccess', function() {
    $scope.loadMore();
  });

  // THIS METHOD LOADS 4 LOCAL TEST ITEMS WITH THE ADSSERVICE
  //$scope.ads = ads;
})
and
.service('AdsService', function($q) {

  return {
    ads : [
        { shortrelativetime:'30 min ago', title: 'TST อาหารเสริมเพี่มความสูง', group:'Vehicles', category:'Cars', province:'Vientiane Capital', district:'Xaythany', price:'24000', currency:'USD', photo:'20140202-040753-c1395444fd.jpg', id: 1 },
        { shortrelativetime:'1 day ago', title: 'TST Samsung Galaxy Grand', group:'High Tech', category:'Phones', province:'Vientiane Capital', district:'Xaythany', price:'6000', currency:'THB', photo:'20140218-101800-1602504d17.jpg', id: 5 },
        { shortrelativetime:'1 day ago', title: 'TST ຂາຍດິນປຸກສ້າງ', group:'Real Estate', category:'Land or House', province:'Vientiane Capital', district:'Xaythany', price:'850000', currency:'THB', photo:'20140715-080420-4a0ba40b89.jpg', id: 6 },
        { shortrelativetime:'08 Jun 2014', title: 'TST HTC One', group:'High Tech', category:'Phones', province:'Vientiane Capital', district:'Xaythany', price:'12000', currency:'THB', photo:'20140604-083644-046276fe30.jpg', id: 9 }
    ],
    getAds: function() {
        return this.data
    },
    getAd: function(adId) {
        var dfd = $q.defer()
        this.ads.forEach(function(ad) {
            if (ad.id === adId) dfd.resolve(ad)
        })

        return dfd.promise
    }

  }
})

ionic framework Making a Signature Drawpad

ionic framework Making a Signature Drawpad


Ionic Framework Making a Signature Drawpad  today discussed this task is Recently I was working on some app and wanted an opportunity for the user to write something down. As I was working with the html5 canvas, I found a very good looking library which I want to show you today: The signature pad. This library allows to draw on your device, with not just a normal bold line but with a quite realistic appeal. Let’s make a simple app to test it!

ionic framework Making a Signature Drawpad
ionic framework Making a Signature Drawpad


Setup a simple App



ionic start devdactic-signature blank
cd devdactic-signature
bower install --save signature_pad
I like to install those packages whenever possible through bower, as it makes managing those dependencies a lot easier. As bower will install our libs always to the same folder, we can go ahead and include the js file at the top of our index.html file:

<script src='lib/signature_pad/signature_pad.js'></script>

Include the Signature Pad functionalities

To use the library, we must define a canvas element inside our index.html which will be the area for the user to draw his signature (or anything else). For this tutorial, we will just have a tiny area at the top, which has the signatureCanvas id so we can get it later in our controller. Additionally I created 2 buttons, which can clear the area or save the current content of the area. Below we have a image, which will show our last saved signature from the canvas. So go ahead and replace everything inside the body with this:

<body ng-app='starter' ng-controller='SignatureCtrl'>
 
    <ion-pane>
      <ion-header-bar class='bar-calm'>
        <h1 class='title'>Devdactic Signature Drawpad</h1>
      </ion-header-bar>
 
      <ion-content class='has-header padding' scroll='false'>
          <canvas id='signatureCanvas' width='300' height='180' style='border: 1px solid black;'></canvas>
          <div class='button-bar'>
              <a class='button button-energized' ng-click='clearCanvas()'>Clear</a>
              <a class='button button-balanced' ng-click='saveCanvas()'>Save</a>
          </div>
          <br>
          <img ng-src='{{signature}}'/>
      </ion-content>
    </ion-pane>
  </body>
We have now defined everything we need inside our index, now we will create the controller which will use the signature pad functionality. Open your app.js and add this:

.controller('SignatureCtrl', function($scope) {
    var canvas = document.getElementById('signatureCanvas');
    var signaturePad = new SignaturePad(canvas);
 
    $scope.clearCanvas = function() {
        signaturePad.clear();
    }
 
    $scope.saveCanvas = function() {
        var sigImg = signaturePad.toDataURL();
        $scope.signature = sigImg;
    }
})
First of all, we get our canvas element through our defined id. Afterwards, we create a new SignaruePad from our canvas element. Now we can simply call functions on this element, thats all! Our clearCanvas() will, well, obviously just clear the canvas drawing area, and our saveCanvas() function gets the image data from the canvas by calling the toDataURL() on our signature pad. This info can be directly used to update our image below.

These are just some simple functions, there are some more things you can edit, which include:

  • dotSize – Size of dot
  • minWidth – Minimum size of a line
  • maxWidth – Maximum sizw of a line
  • backgroundColor – Color used when the canvas is cleared
  • penColor – Color of your line
  • onBegin & onEnd – Callback functions


Ionic Framework, Cordova and File API – A Media Player App

Ionic Framework, Cordova and File API – A Media Player App

Ionic Framework, Cordova and File API - A media Player App Previously Ionic Framework mostly disscued today Ionic Framework How to add media Player Disscussed.  Here Fully Explained this task follow us.
Cordova and File API – A Media Player App
Cordova and File API – A Media Player App

This Post Main reason build a  Media player using Ionic Framework and Cordova plugins. The media player will app show a player interface and a couple of buttons. The user can browse through the filesystem and pick a file to play. The initial request was to play both Audio and Video files inline. But I was only able to get the Audio files to play inline where as the Video will be launched in the device default video player.

Requisites:



The first thing we are going to do is update index.html. Open www/index.html in your favorite editor and update it as below

<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="cordova.js"></script> <!-- your app's js --> <script src="js/app.js"></script> <script src="js/audio.service.js"></script> <script src="js/controllers.js"></script> </head> <body ng-app="starter"> <ion-nav-view></ion-nav-view> </body> </html>
We have referred the audio service JS code that consist of the logic to deal with the Media API and the controllers file which consist of the controller logic.

Next, open www/templates/menu.html. We will update this file with fewer menu items



<ion-side-menus enable-menu-with-back-views="false">
    <ion-side-menu-content>
        <ion-nav-bar class="bar-assertive">
            <ion-nav-back-button>
            </ion-nav-back-button>
            <ion-nav-buttons side="left">
                <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
                </button>
            </ion-nav-buttons>
        </ion-nav-bar>
        <ion-nav-view name="menuContent"></ion-nav-view>
    </ion-side-menu-content>
    <ion-side-menu side="left">
        <ion-header-bar class="bar-assertive">
            <h1 class="title">Menu</h1>
        </ion-header-bar>
        <ion-content>
            <ion-list>
                <ion-item nav-clear menu-close ng-click="player()">
                    Player
                </ion-item>
                <ion-item nav-clear menu-close href="#/app/browse">
                    Browse
                </ion-item>
            </ion-list>
        </ion-content>
    </ion-side-menu>
</ion-side-menus>
Now, we will clean up and rename the required files inside www/templates folder


  • Rename login.html to player.html
  • Delete playlist.html
  • Delete playlists.html
  • Delete search.html

Open www/templates/player.html and update it as below

<ion-modal-view>
    <ion-header-bar class="bar-assertive">
        <h1 class="title">Player</h1>
        <div class="buttons">
            <button class="button button-clear" ng-click="hidePlayer()">Hide</button>
        </div>
    </ion-header-bar>
    <ion-content class="padding">
        <div class="list card">
            <div class="item">
                <h2><i class="icon ion-ios-musical-notes"></i> {{name || '--'}}</h2>
                <p>{{path || '--'}}</p>
            </div>
            <div class="item item-body">
                <div ng-hide="loaded">
                    <label>Please select a Media file to play</label>
                </div>
                <div ng-show="loaded" style="height: 30px; width: {{position}}%; transition: width 0.2s; background: #e42012;">
                </div>
            </div>
            <div class="item tabs tabs-secondary tabs-icon-left">
                <a class="tab-item" href="javascript:" ng-click="resumeAudio()" ng-hide="isPlaying || !loaded">
                    <i class="icon ion-ios-play"></i> Play
                </a>
                <a class="tab-item" href="javascript:" ng-click="pauseAudio()" ng-show="isPlaying">
                    <i class="icon ion-pause"></i> Pause
                </a>
                <a class="tab-item" href="javascript:" ng-click="stopAudio()" ng-show="isPlaying">
                    <i class="icon ion-stop"></i> Stop
                </a>
            </div>
        </div>
    </ion-content>
</ion-modal-view>
This template will be shown when we init the Ionic Modal. This Modal will always be in the background while the app is running.

This template is the base for showing the audio player. Line 18 consists of the logic to show the seek bar. Line 22 shows the play button, when we have paused the video using the button on line 25. We can also stop the media play back completely using the Stop button.

As you can see from the directives on these buttons, they are subjected to visibility based on the state of the audio file.

Next, open www/templates/browse.html and update it as below
<ion-view view-title="Browse">
    <ion-content>
        <ion-item class="item-icon-left item-icon-right" ng-repeat="file in files" type="item-text-wrap" ng-click="showSubDirs(file)">
            <i class="icon" ng-class="{'ion-android-folder' : file.isDirectory, 'ion-eye' : (!file.isDirectory && !file.isUpNav), 'ion-arrow-up-c' : file.isUpNav}"></i>
            <h2>{{file.name}}</h2>
            <p>Location : {{file.fullPath}}</p>
            <i class="icon ion-chevron-right icon-accessory" ng-show="file.isDirectory"></i>
        </ion-item>
    </ion-content>
</ion-view>
This is a very simple template drive by the files[]  from scope. When the user launches the browse page, we will query the file system and show the root files. Once the user clicks on a particular folder, we query the file system API passing in the current folder as the root and fetch its children.

And when a user selects a file, we check if it is of the type audio or video and then play it. Else we will show a message that we cannot play the selected file.

This completes all our templates. We will now work with the Audio Service. Open www/js folder and create a new file named audio.service.js and update it as below.

angular.module('starter.services', [])
 
.service('AudioSvc', [function() {
 
  var AudioSvc = {
    my_media: null,
    mediaTimer: null,
    playAudio: function(src, cb) {
      var self = this;
 
      // stop playing, if playing
      self.stopAudio();
 
      self.my_media = new Media(src, onSuccess, onError);
      self.my_media.play();
 
      if (self.mediaTimer == null) {
        self.mediaTimer = setInterval(function() {
          self.my_media.getCurrentPosition(
            function(position) {
              cb(position, self.my_media.getDuration());
            },
            function(e) {
              console.log("Error getting pos=" + e);
            }
          );
        }, 1000);
      }
 
      function onSuccess() {
        console.log("playAudio():Audio Success");
      }
 
      // onError Callback
      //
      function onError(error) {
        // alert('code: ' + error.code + '\n' +
        //     'message: ' + error.message + '\n');
 
        // we forcefully stop
 
      }
 
    },
 
    resumeAudio: function() {
      var self = this;
      if (self.my_media) {
        self.my_media.play();
      }
    },
    pauseAudio: function() {
      var self = this;
      if (self.my_media) {
        self.my_media.pause();
      }
    },
    stopAudio: function() {
      var self = this;
      if (self.my_media) {
        self.my_media.stop();
      }
      if (self.mediaTimer) {
        clearInterval(self.mediaTimer);
        self.mediaTimer = null;
      }
    }
 
  };
 
  return AudioSvc;
}])

Animate popover for IONIC Framework

IONIC Framework PopOver

$ionicPopover

Instantiated by the $ionicPopover service.

Animate popover
Animate popover


Animate popover Today Discussed Ionic Framework popover first discussed popover controller and method.  Be sure to call remove() function.  when you are done with each popover

Three types Popover Events
  • popover.shown
  • popover.hidden
  • popover.removed

Methods

Create a New Popover controller instance.


Param Type Details
options object An options object with the following properties:

                               {object=} scope The scope to be a child of. Default: creates a child of $rootScope.
                              {boolean=} focusFirstInput Whether to autofocus the first input of the popover when shown. Default: false.
                              {boolean=} backdropClickToClose Whether to close the popover on clicking the backdrop. Default: true.
                              {boolean=} hardwareBackButtonClose Whether the popover can be closed using the hardware back button on Android and similar devices. Default: true.


isShown()

Boolean whether this popover is currently shown.

Hide()

Hide this popover instance.

Popover timeout or some function hide this popover a promise which is resolved when the popover is finished animating out.

removed()

popover removed this function instance from the DOM and clean up.

Popover removed or finished animating out.

Animate popover

Popover Example code.

view.html
<p>
  <button ng-click="openPopover($event)">Open Popover</button>
</p>

<script id="my-popover.html" type="text/ng-template">
  <ion-popover-view>
    <ion-header-bar>
      <h1 class="title">This my Popover</h1>
    </ion-header-bar>
    <ion-content>
      Hello!
    </ion-content>
  </ion-popover-view>
</script>


Controller.js
angular.module('testApp', ['ionic'])
.controller('MyController', function($scope, $ionicPopover) {

  // .fromTemplate() method
  var template = '<ion-popover-view><ion-header-bar> <h1 class="title">My Popover Title</h1> </ion-header-bar> <ion-content> Hello! </ion-content></ion-popover-view>';

  $scope.popover = $ionicPopover.fromTemplate(template, {
    scope: $scope
  });

  // .fromTemplateUrl() method
  $ionicPopover.fromTemplateUrl('my-popover.html', {
    scope: $scope
  }).then(function(popover) {
    $scope.popover = popover;
  });


  $scope.openPopover = function($event) {
    $scope.popover.show($event);
  };
  $scope.closePopover = function() {
    $scope.popover.hide();
  };
  //Cleanup the popover when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.popover.remove();
  });
  // Execute action on hide popover
  $scope.$on('popover.hidden', function() {
    // Execute action
  });
  // Execute action on remove popover
  $scope.$on('popover.removed', function() {
    // Execute action
  });
});

Ionic Framework Session Controller

Ionic Framework Session Controller

Ionic Framework Session 

Ionic Framework Session Controller is two controllers you create in this module use the Session service defined in the starter.services module. To add starter.services as a dependency to the starter.controller module:

  1. Open conference/www/js/controllers.js
  2. Add starter.services as a dependency to make the Session service available to the controllers:
angular.module('starter.controllers', ['starter.services'])

Implement the Session

  1. In controllers.js, delete PlayListsCtrl (plural)
  2. Replace it with a controller named SessionsCtrl that retrieves the list of conference sessions using the Session service and stores it in a scope variable named sessions:
.controller('SessionsCtrl', function($scope, Session) {
    $scope.sessions = Session.query();
})
or

.controller('SessionCtrl', function($scope, $stateParams, Session) {
    $scope.session = Session.get({sessionId: $stateParams.sessionId});
});
Ionic Framework Session stored and Login your username Ionic Login Authentication Click Here

Ionic Framework Flashlight

Ionic Framework Flashlight

flashlight
Flashlight
I am trying to create an app using the Ionic Framework  and Plugin store ngCordova

I have Following Instruction to get the Flashlight working by

Installing ngCordova Plugin with bower

Including ngCordova.js in a script tag before ngCordova.js 

Installing the necessary plugin with cordova.More Ionic Framework


Flashlight Cordova Plugin:



cordova plugin add https://github.com/EddyVerbruggen/Flashlight-PhoneGap-Plugin.git



Example Code:

module.controller('MyCtrl', function($scope, $cordovaFlashlight) {

  $cordovaFlashlight.available().then(function(availability) {
    var avail = availability; // is available
  }, function () {
    // unavailable
  });

  $cordovaFlashlight.switchOn()
    .then(
      function (success) { /* success */ },
      function (error) { /* error */ });

  $cordovaFlashlight.switchOff()
    .then(
      function (success) { /* success */ },
      function (error) { /* error */ });

  $cordovaFlashlight.toggle()
    .then(function (success) { /* success */ },
      function (error) { /* error */ });
});

Ionic Framework Login Authentication from database

ionic


Angularjs + Cordova = Ionic previousle ionic framework previously discussed. Ionic Framework Basically first Login authentication from database. I choose front end ionic framework and backend core php  simple Login authentication access database.

Ionic Framework

Controller.js

.controller('RegistrationCtrl', function ($scope, LoginService) {
    $scope.login = function (userLogin) {
        LoginService.loginUser(userLogin)
        .then(function (data) {
            //log in successfull
        }, function (data) {
            //log in failed
        });
    };
    $scope.register = function (reg) {
       LoginService.registerUser(reg)
        .then(function (resp) {
            // registration success
        }, function (resp) {
            //registration error
        });      
    };        
})


Services

Ionic Framework is work only Web services.


.service('LoginService', function ($q, $http) {
    return {
        loginUser: function (loginData) {
            var deferred = $q.defer(),
                promise = deferred.promise;
            $http({
                url: 'http://someurl/login.php',
                method: "POST",
                data: loginData,
                headers: {'Content-Type': 'application/json'}
            })
                .then(function (response) {
                    if (response.data.error.code === "000") {
                        console.log("User login successful: " + JSON.stringify(response.data));
                        deferred.resolve(response.data);
                    } else {
                        console.log("User login failed: " + JSON.stringify(response.data.error));
                        deferred.reject(response.data);
                    }
                }, function (error) {
                    console.log("Server Error on login: " + JSON.stringify(error));
                    deferred.reject(error);
                });
            promise.success = function (fn) {
                promise.then(fn);
                return promise;
            };
            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            };
            return promise;
        },
        
        registerUser: function (regData) {
            var deferred = $q.defer(),
                promise = deferred.promise;
            
            $http({
                url: 'http://someurl/register.php',
                method: "POST",
                data: regData,
                headers: {'Content-Type': 'application/json'}
            }).then(function (response) {
                if (response.data.error.code === "000") {
                    console.log("User login successful: " + JSON.stringify(response.data));
                    deferred.resolve(response.data);
                } else {
                    console.log("User login failed: " + JSON.stringify(response.data.error));
                    deferred.reject(response.data);
                }
            }, function (error) {
                console.log("Server Error on login: " + JSON.stringify(error));
                deferred.reject(error);
            });
            
            promise.success = function (fn) {
                promise.then(fn);
                return promise;
            };
            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            };
            return promise;
        }
    };
});


Login.php

<?php

$postdata = file_get_contents("php://input");
$loginData = json_decode($postdata);
$email = $loginData->email;
$password = $loginData->password;

$userData = array('userID' => '',
'firstName' => '',
'lastName' => '',
'phone' => '',
'email' => '',
'active' => '');

mysql_connect("IP address of DB", "DB user name", "DB password") or die('{"userData":'.json_encode($userData).', "error": {"code": "003", "message": "Login error! Code: 003"}}'); // Connect to database server(localhost) with username and password.
mysql_select_db("table name") or die('{"userData":'.json_encode($userData).', "error": {"code": "004", "message": "Login error! Code: 004"}}'); 

if(!empty($email) && !empty($password)){

//echo($email.'  '.$password);

$email = mysql_escape_string($email);
$password = mysql_escape_string(md5($password));

$results = mysql_query("SELECT id, fname, lname, phone, email, password, active FROM users WHERE email='".$email."' AND password='".$password."' LIMIT 1") or die('{"error":"Login error! Code: 003"}'); 
$match  = mysql_num_rows($results);

$res = mysql_fetch_assoc($results);

if($match > 0 ){
if ($res['active'] = 1) {
// login success
$userData['userID'] = $res['id'];
$userData['firstName'] = $res['fname'];
$userData['lastName'] = $res['lname'];
$userData['phone'] = $res['phone'];
$userData['email'] = $res['email'];
$userData['active'] = $res['active'];
echo ('{"userData":'.json_encode($userData).',"error":{"code":"000","message":"Logged in as '.$userData['firstName'].' '.$userData['lastName'].'."}}');
} else {
echo('{"userData":'.json_encode($userData).', "error":{"code":"001","message":"Your account has not been ativated. Please verify your account by clicking on the link in the activation email sent when you registered.\r\n If you did not receive an email, click on the Resend Activation Email link and make sure the email is not being blocked by your spam filter."}}');
}
}else{
// login failed
echo ('{"userData":'.json_encode($userData).', "error": {"code": "002","message": "The email or password you entered is incorrect."}}');
}
} else {
// something failed with submitting data, should never get here!
echo('{"userData":'.json_encode($userData).', "error": {"code":"005", "message": "Login error! Code: 005"}}');
}
?>



Disclaimer: Not all these snippet are written by me. Some of them are collected from other sources on Internet.

Simple Ionic App

Welcome This My First App for Ionic Framework

Ionic Framework is new Programming Language related to angularjs same structor and advanced script is Ionic and Looking very nice and faster loading my first simple App for ionic framework.

This App Create to "Welcome This My First App for Ionic Framework" couple different variations to get started towards your first ionic App.


HTML Code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
   <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <link href="http://code.ionicframework.com/1.0.0/css/ionic.min.css" rel="stylesheet">
    <script src="http://code.ionicframework.com/1.0.0/js/ionic.bundle.js"></script>
  </head>
  <body>
 Welcome This My First App for Ionic Framework
  </body>
</html>

App Module

Module Make this an Ionic App similarly Angularjs Concept.

<body ng-app="ionicApp">
angular.module('ionicApp', ['ionic']);

<link href="http://code.ionicframework.com/1.0.0/css/ionic.min.css" rel="stylesheet">
<script src="http://code.ionicframework.com/1.0.0/js/ionic.bundle.js"></script>
<script src="app.js"></script>

Directives


<ion-header-bar class="bar-stable">
 <h1 class="title">Welcome This My First App for Ionic Framework</h1>
</ion-header-bar>

<ion-content class="padding">
 <p>How is My app</p>
</ion-content>







Introduction of Ionic Framework


What is Ionic Framework?

    Ionic Framework is Very Powerful HTML5 SDK is creating Mobile apps using web technologies like HTML, CSS and javascript. Ionic framework is used main Reson is nice look and UI interaction of your app. That means we aren't a replacement phoneGap or your favorite javascript framework.

Ionic Framework is Angulajs Advanced Program is Ionic Cordova + Angularjs =  Ionic Framework

Download Ionic Framework

Click Here ionicframework.com 

How Install Ionic Framework?

Step 1.  First  Install Node.js(Node 5 Does not working  at the moment).
Step 2.  Install the Latest Cordova and ionic Command-line Follow the comment code.

Install ios and Android Platform

                                                    $ npm install -g cordova ionic


Start a Project

Create an Ionic project using one of our ready-made app templates, or a blank one to start fresh.


                  $ ionic start myFirstApp tabs
                  $ ionic start myFirstApp sidemenu      
                  $ ionic start myFirstApp blank

How to Run Ionic Framework ?

   Use the Ionic tool to build, test and run your apps or cordova directly. and ionic view to share your apps with tester and clients to easily test on new devices

   Commend Line:

            $ cd myFirstApp
            $ ionic platform add ios
            $ ionic build ios
            $ ionic emulate ios