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

标签 javascript angularjs

这是我的代码:

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.factory:

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 调用你的服务方法,它应该从 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
   })
};

关于javascript - 从输入中获取字符串并在 AngularJS 中发出 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331983/

相关文章:

javascript - 允许访问 android 中的本地 Assets

javascript - Svelte 仅支持 es6+ 语法。将您的 'compilerOptions.target' 设置为 'es6' 或更高

javascript - CSS 过渡 : Cover Image From Bottom To Top

javascript - 将图像上传到服务器 Angular JS

javascript - new YT.Player() 正在开发中,但不在生产中

javascript - 由 Javascript 填充的 QML ListView

javascript - 为什么扩展语法适用于原语和函数?

javascript - 使用 Node js、AngularJs 和 JWT 使用用户名和密码进行身份验证

html - 为什么 AngularJS ng-view 在本地不起作用?

angularjs - Angular GET 请求陷入循环