I am trying to do the exact same thing like this guy: How to send data from input to service? ,and I did copy/paste every offered solution, but I couldnt manage to make it work. Here is my starting point, when I write the code like this, it works fine:
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>
Now, I am trying to think of a way to get the value from an input field, pass that value into var town, and then refresh the view with the new info, with a single button click. The idea is to make it possible for users to search and get the info for any city available on this API. Please help, I am gonna go nuts with trying to make this work, and I am very new to angular.
A few parts - first you need to make your factory return a callable function that takes town
as a param (also going to use .then
to return a 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;
})
}
}
}]);
Now, make a controller function to handle your click event and call your factory:
$scope.getWeather = function(town) {
forecastBG.getWeatherForTown(town).then(function(data) {
$scope.fiveDay = data;
});
}
And update the view to call this method and pass in your input
model:
<input type="text" ng-model="townToSearchFor" />
<button ng-click="getWeather(townToSearchFor)" ng-disabled="!townToSearchFor">Get Weather!</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.