Skip to content

Instantly share code, notes, and snippets.

@nikoloza
Last active May 2, 2024 02:29
Show Gist options
  • Save nikoloza/9018ee9c3fbad07292cc to your computer and use it in GitHub Desktop.
Save nikoloza/9018ee9c3fbad07292cc to your computer and use it in GitHub Desktop.
[Depricated - it's no longer free] Universal currency exchanger in Angular.js using freecurrencyconverterapi.com public API (ES5)
app.service('CurrencyExchange', function($http, $q) {
// using public API for currency exchange rates
return function (from, rates) {
var deferred = $q.defer();
var base = from.toUpperCase();
var currencies = [];
if (typeof rates === 'string') {
currencies = base + '_' + rates.toUpperCase();
}
else {
rates.forEach(function(value){
currencies.push(base + '_' + value.toUpperCase());
});
currencies = currencies.join(',');
}
$http.jsonp('http://www.freecurrencyconverterapi.com/api/v3/convert?q=' + currencies + '&compact=ultra&callback=JSON_CALLBACK')
.success(function(data) {
var prettyData = {
base: base,
rates: []
};
Object.keys(data).forEach(function(key){
prettyData.rates.push({
key: key.split('_')[1],
value: data[key]
});
});
deferred.resolve(prettyData);
});
return deferred.promise;
};
});
@nikoloza
Copy link
Author

ngCurrencyExchange

Controller should look like this:

app.controller('CurrencyCtrl', function($scope, CurrencyExchange){

  CurrencyExchange('GEL', ['USD', 'GBP', 'EUR']).then(function(currencies){
    $scope.base = currencies.base;
    $scope.rates = currencies.rates;
  });

});

and the view:

ul.currency(ng-controller='CurrencyCtrl')
  li(ng-repeat="rate in rates")
    | 1 {{ base }} = {{ rate.value }} {{ rate.key }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment