Thursday 29 December 2016

Real Time Currency Converter in AngularJS using Yahoo Finance API

index.html

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="invoice3.js"></script>
<script src="finance3.js"></script>

<div ng-app="invoice3" ng-controller="InvoiceController as invoice">

  <b>Invoice:</b>

  <div>
    Quantity: <input type="number" min="0" ng-model="invoice.qty" required ><br><br>
  </div>

  <div>
    Costs: <input type="number" min="0" ng-model="invoice.cost" required ><br><br>
    <select ng-model="invoice.inCurr">
      <option ng-repeat="c in invoice.currencies">{{c}}</option>
    </select>
  </div>

  <div><br>
    <b>Total:</b>
    <span ng-repeat="c in invoice.currencies">
      {{invoice.total(c) | currency:c}} &nbsp;&nbsp;&nbsp;
    </span><br>

<span>&nbsp;&nbsp;{{invoice.CurrentDate | date:'dd/MM/yyyy hh:mm:ss a'}}</span>  </div>
</div>

invoice3.js

angular.module('invoice3', ['finance3'])
.controller('InvoiceController', ['currencyConverter', function InvoiceController(currencyConverter) {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = currencyConverter.currencies;
  this.CurrentDate = new Date();

  this.total = function total(outCurr) {
    return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
  };


}]);


finance2.js

angular.module('finance3', [])
.factory('currencyConverter', ['$http', function($http) {
  var YAHOO_FINANCE_URL_PATTERN =
        '//query.yahooapis.com/v1/public/yql?q=select * from ' +
        'yahoo.finance.xchange where pair in ("PAIRS")&format=json&' +
        'env=store://datatables.org/alltableswithkeys';
  var currencies = ['USD', 'EUR', 'CNY'];
  var usdToForeignRates = {};

  var convert = function(amount, inCurr, outCurr) {
    return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
  };

  var refresh = function() {
    var url = YAHOO_FINANCE_URL_PATTERN.
               replace('PAIRS', 'USD' + currencies.join('","USD'));
    return $http.get(url).then(function(response) {
      var newUsdToForeignRates = {};
      angular.forEach(response.data.query.results.rate, function(rate) {
        var currency = rate.id.substring(3,6);
        newUsdToForeignRates[currency] = window.parseFloat(rate.Rate);
      });
      usdToForeignRates = newUsdToForeignRates;
    });
  };

  refresh();

  return {
    currencies: currencies,
    convert: convert
  };

}]);


Output:







2 comments:

  1. Exactly, you're very kind of us about comment!. convert money online

    ReplyDelete
  2. Excellent to be visiting your blog again, it has been months for me. Rightly, this article that I've been served for therefore long. I want this article to finish my assignment within the faculty, and it has the same topic together with your article. Thanks for the ton of valuable help, nice share. buy-now-pay-later-desktop-computers

    ReplyDelete