[英]AngularJS Help: Connecting a Search Input into an REST Interface
最近几天我一直在学习AngularJS,但是我只停留在一节中。 我想做的是允许用户输入搜索(当然是在输入小部件内),我希望将搜索连接到Online API(OpenWeatherAPI)并从在线提取JSON数据。 然后,我希望结果显示在网页中。
我已经完成了使用AngularJS提取JSON数据的源代码。 我只是坚持将搜索查询连接到API。 以下是提取REST API的源代码:
9 var app = angular.module('oMoonShine', []);
10
11 // Note: Controller To Access Weather Data From OpenWeatherAPI (Content Type: JSON)
12 app.controller('FetchController', function ($scope, $http) {
13 $http.get("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139", request)
14 .then(function (response) {
15 if (response.status == 200) {
16 // Note: Important To Print Your Response To Anaylse The JSON Recieved
17 // Note: For Example OpenWeatherAPI Add Additional Param So Have it
18 // Note: Like <code>$scope.info = response.data;</code> To Anaysle It
19 $scope.info = response.data;
20 }
21 });
22
23 // Note: Request Object For Extra Types
24 var request = {
25 headers: 'application/json',
26 method: 'GET'
27 };
28 });
这是您访问数据的方式: 有用的小提琴
HTML:
<div ng-controller="MyCtrl">
The weather from {{weatherLocation}}
<p>The wind speed is: {{windSpeed}} and the degree is {{windDegree}}</p>
</div>
控制器:
angular.module('myApp',[]).controller("MyCtrl", MyCtrl);
function MyCtrl($scope, $http) {
$http.get("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139").success(function(data){
$scope.weatherLocation = data.name;
$scope.windSpeed = data.wind.speed;
$scope.windDegree = data.wind.deg;
console.log(data)
})
}
编辑
阅读您的评论后,请参阅我更新的小提琴
<div ng-controller="MyCtrl">
The weather from {{weatherLocation}}
<p>The wind speed is: {{windSpeed}} and the degree is {{windDegree}}</p>
<input type="text" ng-model="location"/>
<button ng-click="findWeather()">submit</button>
</div>
angular.module('myApp',[]).controller("MyCtrl", MyCtrl);
function MyCtrl($scope, $http) {
$scope.location = "";
$scope.findWeather = function(){
http://api.openweathermap.org/data/2.5/weather?q=washington
$http.get(" http://api.openweathermap.org/data/2.5/weather?q=" + $scope.location).success(function(data){
$scope.weatherLocation = data.name;
$scope.windSpeed = data.wind.speed;
$scope.windDegree = data.wind.deg;
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.