【发布时间】:2017-04-29 19:27:32
【问题描述】:
AngularJS 1.6 的所有文档都非常模糊。每个人都有关于如何执行 $http.get 请求的教程,但没有关于如何正确设置 1.6 版的 $http.post 请求的教程。
我要做的只是设置一个控制器,为我的迷你项目提供功能,允许用户在主页上的输入框中输入他/她的城市,当他们提交时,信息他们的预测将出现在“预测”页面上。因此,理论上,控制器会将数据“POST”到 URL 中,以便能够从 Open Weather API 检索信息。 Routes 和其他一切工作都很好......我只需要这个 POST 方法的帮助。
对于我的代码看起来难以理解,我深表歉意。我刚刚发布了我所拥有的。
顺便说一句,有没有人有真正好的 AngularJS 1.6 文档资源?
(function () {
'use strict';
// MODULE
angular.module("WeatherApp", ['ngRoute', 'ngResource', 'http'])
// ROUTES
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
})
.when('/forecast', {
templateUrl: 'templates/forecast.html',
controller: 'forecastCtrl'
});
})
// SERVICES
.service('cityService', function () {
this.city = "Chicago";
})
// CONTROLLERS
.controller("homeCtrl", function ($scope, cityService) {
$scope.city = cityService.city;
$scope.$watch('city', function () {
cityService.city = $scope.city;
});
})
.controller("forecastCtrl", function ($scope, $http, cityService) {
$scope.city = cityService.city;
$http.post("http://api.openweathermap.org/data/2.5/forecast/daily", {q: $scope.city, cnt: 2, appid: "8a3dfe91838e8409da30958ed6b68932"}).then(function (data) {
console.log();
});
});
})();
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h4>Forecast by City</h4>
<div class="form-group"><input ng-model="city" type="text" class="form-control"></div>
<a href="#!/forecast" class="btn btn-primary">Get Forecast</a>
</div>
</div>
【问题讨论】:
-
您需要使用获取预测按钮(或用作链接的按钮)的
ng-click来调用在$scope上定义的方法,并且在该方法中您需要使用$http.post.$http.post看起来不错。您不需要多个控制器来执行此操作。 -
你能给我一个完整的例子吗?