我遇到了向服务发送数据表单输入的问题。 例如,我有一个输入:
<input type="text" class="form-control" placeholder="City name...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
正在为rest api提供数据的服务:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
单击“Go”按钮构建我自己的api链接后,如何从输入中发送城市名称?然后在视图中显示这些数据? 我的意思是这样的http://api.openweathermap.org/data/2.5/forecast/city?q=VALUE_FROM_THE_INPUT&units=metric&mo
答案 0 :(得分:1)
您应该为输入分配ng-model
指令,如下所示:
<input type="text" class="form-control" placeholder="City name..." ng-model="city.name">
为您的按钮分配ng-click
指令,如下所示:
<button class="btn btn-default" type="button" ng-click="getForecast(city)">Go!</button>
最后,将getForecast
函数添加到控制器中,如下所示:
$scope.getForecast = function (city) {
forecast.getForecast($scope.city).then(function (data) {
// do something with the response
}, function (err) {
// do something about the error
});
}
为此,您应该将服务更改为以下内容:
app.factory('forecast', ['$http', function($http) {
return {
getForcast: function (city) {
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=' + city.name + '&units=metric&mo');
}
};
}]);
答案 1 :(得分:0)
你的HTML:
<input type="text" class="form-control" placeholder="City name..." ng-model="city">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="go()">Go!</button>
</span>
你的工厂:
app.factory('forecast', ['$http', function($http) {
this.sendAPIRequest = function(city){
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?q='+city+'&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
return this;
}]);
你的控制器:
app.controller('myCtrl', ['$scope', 'forecast', function ($scope, forecast) {
$scope.go = function(){
$scope.data = forecast.sendAPIRequest($scope.city);
};
}])
答案 2 :(得分:0)
您似乎在问几个问题,但是让我们从“GO”开始使用输入进行链接。因为你正在使用角度工厂,你可能想要使用控制器或其他东西:
HTML:
<div ng-controller="formCtrl">
<input type="text" class="form-control" placeholder="City name..." ng-model="city">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="goToUrl(city)">Go!</button>
</span>
</div>
现在您想将该城市传递给网址名称?
app.factory('forecast', ['$http', function($http) {
var forecastFactory = {};
forcastFactory.customUrl = function(city){
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?' + city +'q=Warsaw&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
return forecastFactory;
}]);
app.controller('formCtrl', ['forecast', function(Forecast){
$scope.goToUrl = function(name){
var data = Forecast.customUrl(name);
}
}]);