When using ngModel on the first select, it will store the selected value. To incorporate this into the URL, fetch the data from $scope.fromType and append it like so:
$http.get('http://api.fixer.io/latest?base=' + $scope.fromType.label).then(function(res) {
$scope.fromValue = 1;
$scope.ConvertCurrency();
var i = 0;
angular.forEach(res.data.rates, function(value, key) {
if (key == "USD" || key == "EUR" || key == "CAD") {
$scope.rates.push({ value: value, label: key });
}
i++;
});
});
Update
I assumed a few things here.
- Initially, load all rates in the first select ($scope.getAllRates())
- When a rate is selected in the first select, load rates associated with that currency in the other select ($scope.getRate())
If this applies to your scenario, your view should look like this
<div ng-app="CurrencyConv" ng-controller="ConvertCtrl">
<input type="number" placeholder="0.00" ng-model="fromValue" ng-change="ConvertCurrency();" min='0'>
<select ng-model="fromType" required ng-change="ConvertCurrency(); getRate();" ng-options="f as f.label for f in rates"></select>
<input type="text" placeholder="0.00" ng-model="toValue" ng-change="ConvertCurrency()">
<select ng-model="toType" required ng-change="ConvertCurrency()" ng-options="f as f.label for f in toRates"></select>
</div>
And the controller
App.controller('ConvertCtrl', ['$scope', '$http', function($scope, $http) {
$scope.rates = [];
$scope.toRates = [];
$scope.toType = {};
$scope.fromType = {};
$scope.fromValue = 1;
$scope.getAllRates = function(){
$http.get('https://api.fixer.io/latest').then(function(res) {
angular.forEach(res.data.rates, function(value, key) {
if (key == "USD" || key == "EUR" || key == "CAD") {
$scope.rates.push({ value: value, label: key });
}
});
});
};
$scope.getRate = function(){
$scope.toRates = [];
if(typeof $scope.fromType.label !== undefined){
$http.get('https://api.fixer.io/latest?base=' + $scope.fromType.label).then(function(res) {
$scope.fromValue = 1;
$scope.toValue = 0;
angular.forEach(res.data.rates, function(value, key) {
if (key == "USD" || key == "EUR" || key == "CAD") {
$scope.toRates.push({ value: value, label: key });
}
});
$scope.toType = $scope.toRates[0];
$scope.ConvertCurrency();
});
}
};
$scope.ConvertCurrency = function() {
if($scope.toRates.length > 0){
$scope.toValue = $scope.fromValue * ($scope.toType.value * (1 / $scope.fromType.value));
}
};
//init
$scope.getAllRates();
}]);
Feel free to check out the plunker