第一个选择上的 ngModel (fromType) 将保存选定的值。因此,从 $scope.fromType 获取数据并将其添加到 url,如下所示
$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++;
});
});
更新
好的,所以基本上我在这里做了一些假设。
- 开始时,我们应该在第一个选择中加载所有费率 ($scope.getAllRates())
- 当在第一个选择中选择一个汇率时,我们应该在另一个选择中加载与该货币相关的汇率 ($scope.getRate())
如果是这种情况,你的视图会是这样的
<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>
还有控制器
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();
}]);
Here's一个笨蛋