Interest in //Web //Win //Mobile //Database & //Life

Hybrid Application Development using Ionic, AngularJs, Cordova – Part 3

After completing all the necessary steps described in Part 1 and Part 2 of this series tutorial, you will see the following folder structure in your application directory.

RealExchangeRate-FolderStructure

I will work with the www folder. inside the folder you will get the index.html and js/app.js, these are the two main files you have to work with. Use any of your favorite text editor to open up the files.

As we are going to use AngularJs for the development, first finish up the js/app.js file. You will see the template generated code like this.

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

after the we will add our controller code. I will do step by step explanation but first let me show you the code.

 .controller('realexchangeCtrl',function($scope,$filter,$ionicLoading,$http,$ionicPopup){
        $scope.Data={};
        $scope.Data.amount=1;
        $scope.Data.currentDate=$filter("date")(Date.now(),'yyyy-MM-dd');
        $scope.Data.date=$scope.Data.currentDate;

        var apiKey="your api key";
        var baseUrl="http://openexchangerates.org/api/";

        $scope.url=baseUrl+"latest.json?app_id="+apiKey;
        
        $ionicLoading.show();
        $http.get($scope.url)
            .success(function(response){
                $scope.result=response;                
            })
            .error(function(response,status){
                $scope.showAlert('Error!!!',response.message);
            })
            .finally(function(){
                $ionicLoading.hide();
            });

        $scope.getExchangeRate = function() {

            if($scope.Data.date!=$scope.Data.currentDate)
            {
                $ionicLoading.show();
                $scope.url=baseUrl+"historical/"+$scope.Data.date+".json?app_id="+apiKey;

                $http.get($scope.url)
                    .success(function(response) {
                        $scope.historicalresult = response;
                        fx.rates = response.rates;
                        fx.base = response.base;
                        $scope.exchangeRate=fx($scope.Data.amount).from($scope.Data.fromCurrency).to($scope.Data.toCurrency).toFixed(2);
                    })
                    .error(function(response, status){
                        $scope.showAlert('Error!!!',response.message);
                    })
                    .finally(function(){
                        $ionicLoading.hide();
                    });
            }
            else{
                fx.rates = $scope.result.rates;
                fx.base = $scope.result.base;
                $scope.exchangeRate=fx($scope.Data.amount).from($scope.Data.fromCurrency).to($scope.Data.toCurrency).toFixed(2);
            }
        };
        $scope.doRefresh = function() {
            $http.get($scope.url)
                .success(function(response) {
                    $scope.result = response;                    
                })
                .finally(function() {
                    // Stop the ion-refresher from spinning
                    $scope.$broadcast('scroll.refreshComplete');
                });
        };
        $scope.showAlert = function(alertTitle,alertTemplate) {
            var alertPopup = $ionicPopup.alert({
                title: alertTitle,
                template: alertTemplate
            });
            alertPopup.then(function(res) {
                console.log('Log Error');
            });
        };

})

 

.controller('realexchangeCtrl',function($scope,$filter,$ionicLoading,$http,$ionicPopup){

realexchangeCtrl is the name of our controller and in the function we are adding our dependencies for the controller,then I am just defining some variables in scope. you need to create an account in OpenExchnageRates to get the api key and replace the text with your api Key and then just setting the url to request.

$scope.Data={};
        $scope.Data.amount=1;
        $scope.Data.currentDate=$filter("date")(Date.now(),'yyyy-MM-dd');
        $scope.Data.date=$scope.Data.currentDate;

        var apiKey="your api key";
        var baseUrl="http://openexchangerates.org/api/";

        $scope.url=baseUrl+"latest.json?app_id="+apiKey;

Now going to make a GET request to the api using the url, just before that I am calling the $ionicLoading.show(); this will show a nice loading until it finishes the GET request. If the GET request completes successfully I am keeping the response of the request in $scope.result.

        $ionicLoading.show();
        $http.get($scope.url)
            .success(function(response){
                $scope.result=response;                
            })
            .error(function(response,status){
                $scope.showAlert('Error!!!',response.message);
            })
            .finally(function(){
                $ionicLoading.hide();
            });

Now I will explain the getExchangeRates funciton. First I am checking whether the date selected by user is current date or not, if it is not current date then I have to call the api for historical exchange rate. So I am changing the url to the historical api and making a http GET request.

Then assigning the response.rates and response.base (rates contains all the exchange rate of currency’s against the base currency value, the base currency is in USD for free API)value from the response to the fx.rates and fx.base. oh! what are these two?  The fx.rates and fx.base are from money.js a small javascript library for currency conversion, maintained by Open Exchange Rates. we will include this in our index.html. If any error occurs showing the error as alert using the $scope.showAlert() method that uses $ionicPopup and finally hiding the loader. Open Exchange Rates api also provides a list of currency in this url http://openexchangerates.org/api/currencies.json but I will use currency names from the response.rates here.

$scope.exchangeRate=fx($scope.Data.amount)
                       .from($scope.Data.fromCurrency)
                       .to($scope.Data.toCurrency)
                       .toFixed(2);

this line of code is converting the currency exchange rate and keeping it in two decimal places, which is pretty self explanatory.

$scope.getExchangeRate = function() {

            if($scope.Data.date!=$scope.Data.currentDate)
            {
                $ionicLoading.show();
                $scope.url=baseUrl+"historical/"+$scope.Data.date+".json?app_id="+apiKey;

                $http.get($scope.url)
                    .success(function(response) {
                        fx.rates = response.rates;
                        fx.base = response.base;
                        $scope.exchangeRate=fx($scope.Data.amount).from($scope.Data.fromCurrency).to($scope.Data.toCurrency).toFixed(2);
                    })
                    .error(function(response, status){
                        $scope.showAlert('Error!!!',response.message);
                    })
                    .finally(function(){
                        $ionicLoading.hide();
                    });
            }
            else{
                fx.rates = $scope.result.rates;
                fx.base = $scope.result.base;
                $scope.exchangeRate=fx($scope.Data.amount).from($scope.Data.fromCurrency).to($scope.Data.toCurrency).toFixed(2);
            }
        };

And last of all the doRefresh and showAlert method. The doRefresh method is used to implement the pull to refresh functionality using this directive and for alert popups you can check this one.

$scope.doRefresh = function() {
            $http.get($scope.url)
                .success(function(response) {
                    $scope.result = response;                    
                })
                .finally(function() {
                    // Stop the ion-refresher from spinning
                    $scope.$broadcast('scroll.refreshComplete');
                });
        };
        $scope.showAlert = function(alertTitle,alertTemplate) {
            var alertPopup = $ionicPopup.alert({
                title: alertTitle,
                template: alertTemplate
            });
            alertPopup.then(function(res) {
                console.log('Log Error');
            });
        };

Now we will see the index.html file, inside the head tag I have added the money.js reference and in body tag I am setting the ng-app and ng-controller.

<!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="cordova.js"></script>

    <script src="js/money.js"></script>
    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter" ng-controller="realexchangeCtrl">

  <ion-pane>
      <ion-header-bar class="bar-stable bar-calm">
          <h1 class="title">Real Exchange Rate</h1>
      </ion-header-bar>
      <ion-content >
          <ion-refresher
                  pulling-text="Pull to refresh..."
                  on-refresh="doRefresh()">
          </ion-refresher>
          <div class="list">
              <label class="item item-input item-select">
                  <div class="input-label">
                      From Currency
                  </div>
                  <select ng-model="Data.fromCurrency" ng-change="getExchangeRate()">
                                <option value="">Select</option>
                      <option ng-repeat="(key,value)  in result.rates" value="{{key}}">{{key}}</option>
                  </select>
              </label>
          </div>
          <div class="list">

              <label class="item item-input item-select">
                  <div class="input-label">
                      To Currency
                  </div>
                  <select ng-model="Data.toCurrency" ng-change="getExchangeRate()">
                                 <option value="">Select</option>
                      <option ng-repeat="(key,value) in result.rates" value="{{key}}">{{key}}</option>
                  </select>
              </label>

          </div>

          <div class="list">
              <label class="item item-input">
                  <div class="input-label">
                      Amount
                  </div>
                  <input id="amount" type="number" placeholder="Amount" ng-model="Data.amount" ng-change="getExchangeRate()">
              </label>
          </div>
          <label class="item item-input">
              <span class="input-label">Date</span>
              <input id="rateDate" type="date" ng-model="Data.date" ng-change="getExchangeRate()">
          </label>
          <div class="card" ng-show="exchangeRate">
              <div class="item item-text-wrap" style="text-align:center;">
                  <h1>{{Data.amount}} {{Data.fromCurrency}} = {{exchangeRate}} {{Data.toCurrency}}</h1>
              </div>
          </div>
      </ion-content>
      <div class="bar bar-footer bar-calm">
          <div class="title">&copy 2014 <a href="http://blog.shiefuzzaman.com" target="_blank">Shiefuzzaman</a></div>
      </div>
  </ion-pane>
  </body>
</html>

for the pull down refresher functionality we need this part of code and it has to be the first child of <ion-content></ion-content>

          <ion-refresher
                  pulling-text="Pull to refresh..."
                  on-refresh="doRefresh()">
          </ion-refresher>

I am taking select list that will show the currency list from which currency user want to convert to which currency, on changing the currency it will call the getExchangeRate() method in our controller. Binding the currency list to select element using ng-repeat to the $scope.Data.result.rates

<div class="list">
              <label class="item item-input item-select">
                  <div class="input-label">
                      From Currency
                  </div>
                  <select ng-model="Data.fromCurrency" ng-change="getExchangeRate()">
                                <option value="">Select</option>
                      <option ng-repeat="(key,value)  in result.rates" value="{{key}}">{{key}}</option>
                  </select>
              </label>
          </div>

for amount and date change I am also calling the getExchangeRate() method and at the bottom of the application I am showing the result. I am using ng-show directive to the $scope.exchangeRate because I want to show the result only if there is a valid result. When the user selects only from currency and there is not to currency that time there is no valid exchange rate.

<div class="card" ng-show="exchangeRate">
              <div class="item item-text-wrap" style="text-align:center;">
                  <h1>{{Data.amount}} {{Data.fromCurrency}} = {{exchangeRate}} {{Data.toCurrency}}</h1>
              </div>
          </div>

And that is all, if you want to download the source code click here to download it from github repository.

For publishing your hybrid application to the app market built with Ionic Framework, please follow this link as your guideline.

I wish I could make a video tutorial for this, but I am not getting enough time. hope in near future I will be able to do it. I have just started blogging, for any mistakes please help me with your valuable suggestions.

AngularJsCordovaHybrid AppicationIonic

Md Shiefuzzaman • October 24, 2014


Previous Post

Next Post

Leave a Reply

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