簡體   English   中英

AngularJS幫助:將搜索輸入連接到REST接口

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM