我们是否可以创建动态网址,就像我们从第一个下拉列表中选择一个值时,该网址应为http://api.fixer.io/latest?base=value。
这意味着当我们在第一个下拉列表中选择值(USD)时,在URL(http://api.fixer.io/latest?base=USD)的末尾应用相同的值,并且json数据将来自该URL。
答案 0 :(得分:0)
第一个选择的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++;
});
});
<强>更新强>
好的,基本上我在这里做了一些假设。
如果是这种情况,您的观点将是这样的
<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一名掠夺者
答案 1 :(得分:0)
将ng-model设置为您选择并将该值存储在$ scope中。发出请求时,将该值设置为参数。
$http.get('http://api.fixer.io/latest', { params:{base: $scope.fromType.label}}).then(function(res) {
});
答案 2 :(得分:0)
只需将您的ngModel附加到您的请求网址
即可$scope.makeRequest = function(offset){
$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.ConvertCurrency = function() {
$scope.toValue = $scope.fromValue * ($scope.toType.value * (1 / $scope.fromType.value));
$scope.makeRequest();
};
如果您每次都需要提出不同的请求,则需要在函数中设置请求并调用它。