从输入中获取字符串,并在AngularJS中发出AJAX请求

Take string from input and make an AJAX request in AngularJS

本文关键字:AJAX AngularJS 请求 输入 获取 字符串 并在      更新时间:2023-09-26

这是我的代码:

http://jsfiddle.net/n8t2born/1/

有3个js文件,当我使用静态URL(里面没有inputCity变量)时,它运行得非常好。我应该如何正确地告诉angular从我的输入中获取信息,并将其放入链接中,显示特定城市的天气信息?

这是我的表格:

    <form class="form-container" ng-submit="Weather.getWeather(inputCity)">
        <input class="input-field" type="text" ng-model="inputCity" placeholder="City">
        <input class="button-style" type="submit" value="Show Weather">
    </form>

这是我的角度工厂:

angular
.module('weather.factory', [])
.factory('Weather', [
    '$http',
    function($http) {
        return {
            getWeather : function(inputCity) {
                return $http({
                    url: 'http://api.wunderground.com/api/KEY/conditions/q/' + inputCity + '.json',
                    method: 'GET'
                })
            }
        }
    }
]);

您永远不应该从有promise的控制器中调用您的服务方法,它应该从controller&然后在ajax成功中更新所需的位置数据

HTML

<form class="form-container" ng-submit="submitForm(inputCity)">
    <input class="input-field" type="text" ng-model="inputCity" placeholder="City">
    <input class="button-style" type="submit" value="Show Weather">
</form>

代码

$scope.submitForm =function(inputCity){
   Weather.getWeather(inputCity).success(function(){
      //data updation will lie here
   }).error(function(error){
      //do error handling here
   })
};