Kyle G. Kyle G. - 4 months ago 43
AngularJS Question

How do I correctly bind 'select' option with an API call?

I'm trying to write a simple AngularJS program which makes REST calls to an API that gives data on exchange rates. the app deals with exchange rates, and i'm doing this mainly for educational purposes.
I'm have an issue while attempting to two-way bind data between a select element in the HTML:

<select id="currencySelect"
ng-model="search"
ng-options="currency for (currency, rate) in exRates.rates">
</select>


And my controller:

(function () {
"use strict";
angular.module("exchangeRates")
.controller('getRates', function($scope, $http){
$scope.$watch('search', function() {
fetch();
});
$scope.search = "USD";


function fetch(){
$http.get("http://api.fixer.io/latest?base=" + $scope.search )
.then(function(response){
$scope.exRates = response.data;
});
}});
}());


'search' is bound to the HTML element via ng-model, and works perfectly for the default value set at "USD". However, when I use the select element to select another type of currency, the data bound to 'search' is the rate in the (currency, rate) -- key, value pair.

I want it to take the currency(key) which is being displayed in the select element and bind that to 'search' instead of the rate(value).

For example: If I choose "EUR" in the select element, 'search' is bound to 0.90318 instead of "EUR". The GET request then tries:


http://api.fixer.io/latest?base=0.90318



which does not work.

It may help to look at a sample JSON excerpt:


Source


{ "base":"USD",
"date":"2016-07-13",
"rates": {
"AUD":1.3111,
"BGN":1.7664,
"BRL":3.2981,
"CAD":1.3053,
"CHF":0.98528,
"CNY":6.6905,
"CZK":24.416,
"DKK":6.7177,
"GBP":0.75323,
"HKD":7.7576,
"HRK":6.7677,
"HUF":283.05,
"IDR":13046.0,
"ILS":3.8685,
"INR":67.03,
"JPY":104.61,
"KRW":1143.0,
"MXN":18.316,
"MYR":3.9432,
"NOK":8.4127,
"NZD":1.3687,
"PHP":47.13,
"PLN":3.979,
"RON":4.0565,
"RUB":63.801,
"SEK":8.5231,
"SGD":1.346,
"THB":35.18,
"TRY":2.8944,
"ZAR":14.333,
"EUR":0.90318
}
}



Example of the user interface

Answer

You were close, just need to adjust your ngOptions syntax slightly:

ng-options="currency as currency for (currency, rate) in exRates.rates"

Easy to remember with value as text for item/obj in collection

Comments