我正在尝试构建一个基本的AngularJS天气应用程序,该应用程序从表单中获取用户邮政编码并进行API调用以获取当前预测。该应用程序有2个视图/路线。第一个视图有一个输入字段和一个提交按钮来收集用户的zip。第二个视图将显示预测。
我想要发生的是让用户将一个邮政编码放入表单中,并在提交后,构建一个URL以进行Http请求调用。所以我的最终网址看起来像是:
baseURL + UserZipFromForm + .json
我尝试使用Angular的$ http,但它不会让我传入url的变量,因为它期待一个字符串。我不认为我想做的事情有资格作为查询参数,而且我已经阅读了一些有关创建工厂的事情,但我现在有点转身。
如果我使用ng-Submit来触发构建网址,如何制作$ http请求并将响应放入正确的范围以便在我的预测视图中使用?
HTML:
<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>
JS:
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) {
});
};
}]);