[英]AngularJS, How to get the value from input and place it in a factory?
我正在嘗試像這個家伙一樣做同樣的事情: 如何將數據從輸入發送到服務? ,並且確實復制/粘貼了所有提供的解決方案,但是我無法使其正常運行。 這是我的起點,當我編寫這樣的代碼時,它可以正常工作:
var town="London";
//factory
scotchApp.factory('forecastBG', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/find?q=' + town + '&units=metric&appid=bd82977b86bf27fb59a04b61b657fb6f')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
//controller
scotchApp.controller('beograd', ['$scope', 'forecastBG', function($scope, forecastBG) {
forecastBG.success(function(data) {
$scope.fiveDay = data;
});
}]);
//view
<div class="forecast">
<div ng-controller="beograd" class="first">
<p></p>
<p style="font-size: 130%"> City </p>
<p style="font-size: 130%">{{ fiveDay['list'][0].main.temp }}°C</p>
<p> Wind: {{ fiveDay['list'][0].wind.speed }} m/s</p>
<p> Pressure: {{ fiveDay['list'][0].main.pressure }}hpa</p>
<p> Humidity: {{ fiveDay['list'][0].main.humidity }}%</p>
<p style="font-size: 90%"> Min. temp.: {{ fiveDay['list'][0].main.temp_min }}°C</p>
<p style="font-size: 90%"> Max. temp.: {{ fiveDay['list'][0].main.temp_max }}°C</p>
<p style="font-size: 90%"> {{ fiveDay['list'][0]['weather'][0].description }}</p>
</div>
</div>
現在,我正在嘗試一種方法,可從輸入字段中獲取值,然后將該值傳遞給var town,然后單擊一次按鈕即可使用新信息刷新視圖。 這樣做的目的是使用戶可以搜索並獲取此API上可用的任何城市的信息。 請幫忙,我將不遺余力地嘗試完成這項工作,而且我對棱角也很陌生。
有幾部分-首先,您需要使工廠返回一個以town
作為參數的可調用函數(也將使用.then
返回一個Promise):
scotchApp.factory('forecastBG', ['$http', function($http) {
return {
getWeatherForTown: function(town) {
return $http.get('http://api.openweathermap.org/data/2.5/find?q=' + town + '&units=metric&appid=bd82977b86bf27fb59a04b61b657fb6f')
.then(function(result) {
return result.data;
})
}
}
}]);
現在,創建一個控制器函數來處理您的click事件並致電工廠:
$scope.getWeather = function(town) {
forecastBG.getWeatherForTown(town).then(function(data) {
$scope.fiveDay = data;
});
}
並更新視圖以調用此方法並傳入您的input
模型:
<input type="text" ng-model="townToSearchFor" />
<button ng-click="getWeather(townToSearchFor)" ng-disabled="!townToSearchFor">Get Weather!</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.