Javascript 从AngularJS中的表单字段生成$http请求
我正在尝试构建一个基本的AngularJS天气应用程序,它从表单中获取用户的邮政编码,并进行API调用以获取当前天气预报。该应用程序有2个视图/路线。第一个视图有一个输入字段和一个submit按钮来收集用户的zip。第二个视图将显示预测 我想让用户在表单中输入一个邮政编码,然后在提交后,构建一个url以进行Http请求调用。因此,我的最终url如下所示: baseURL+UserZipFromForm+.json 我尝试使用Angular的$http,但它不允许我为url传递变量,因为它需要字符串。我不认为我正在尝试做的是作为一个查询参数,我读过一些关于创建工厂的东西,但我现在有点改变了 如果我使用ng Submit来触发构建url,那么如何发出$http请求并将响应放入正确的范围,以便在我的forecast视图中使用 html:Javascript 从AngularJS中的表单字段生成$http请求,javascript,angularjs,forms,http,Javascript,Angularjs,Forms,Http,我正在尝试构建一个基本的AngularJS天气应用程序,它从表单中获取用户的邮政编码,并进行API调用以获取当前天气预报。该应用程序有2个视图/路线。第一个视图有一个输入字段和一个submit按钮来收集用户的zip。第二个视图将显示预测 我想让用户在表单中输入一个邮政编码,然后在提交后,构建一个url以进行Http请求调用。因此,我的最终url如下所示: baseURL+UserZipFromForm+.json 我尝试使用Angular的$http,但它不允许我为url传递变量,因为它需要字符
请发布您现有的代码。
baseURL+UserZipFromForm+。'json'
应作为url。上面发布的代码
<div class="text-center">
<h2>Enter Your Zip</h2>
<form name="myForm" ng-submit="submitMyForm()">
<input type="text" ng-model="zipCode" />
<button type="submit" value="Submit">Submit!</button>
</form>
<pre>zip = <span ng-bind="zipCode"></span></pre>
</div>
var myWeather = angular.module('myWeather', ['ngRoute']);
myWeather.config(function($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'views/home.html',
controller : 'mainController'
})
// route for the forecast page
.when('/forecast', {
templateUrl : 'views/forecast.html',
controller : 'mainController'
});
$locationProvider.html5Mode(true);
});
myWeather.controller('mainController', ['$scope', '$http', '$location', function($scope, $http, $location) {
// create a message to display in our view
$scope.greeting = 'Here is the weather for:';
$scope.submitMyForm=function(){
var data= $scope.zipCode;
var url = "https://api.wunderground.com//" + data + ".json"
console.log(url);
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
$scope.weather = response.data.current_observation;
return $scope.weather;
}, function errorCallback(response) {
});
};
}]);