How To Send Data From Input To Service?
I have a problem with a sending data form input to the service. For example I have an input:
Solution 1:
You should assign your input an ng-model
directive, like this:
<inputtype="text"class="form-control" placeholder="City name..." ng-model="city.name">
Assign your button an ng-click
directive, like this:
<button class="btn btn-default"type="button" ng-click="getForecast(city)">Go!</button>
Finally, add getForecast
function to your controller, like this:
$scope.getForecast = function (city) {
forecast.getForecast($scope.city).then(function (data) {
// do something with the response
}, function (err) {
// do something about the error
});
}
For this to work you should change your service to something like this:
app.factory('forecast', ['$http', function($http) {
return {
getForcast: function (city) {
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=' + city.name + '&units=metric&mo');
}
};
}]);
Solution 2:
your HTML :
<input type="text"class="form-control" placeholder="City name..." ng-model="city">
<spanclass="input-group-btn"><buttonclass="btn btn-default"type="button"ng-click="go()">Go!</button></span>
your Factory :
app.factory('forecast', ['$http', function($http) {
this.sendAPIRequest = function(city){
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?q='+city+'&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
returnthis;
}]);
your Controller :
app.controller('myCtrl', ['$scope', 'forecast', function ($scope, forecast) {
$scope.go = function(){
$scope.data = forecast.sendAPIRequest($scope.city);
};
}])
Solution 3:
You seem to be asking a few questions, but lets just start with the "GO" to link using input. since you're using an angular factory you may want to use a controller or something:
HTML:
<divng-controller="formCtrl"><inputtype="text"class="form-control"placeholder="City name..."ng-model="city"><spanclass="input-group-btn"><buttonclass="btn btn-default"type="button"ng-click="goToUrl(city)">Go!</button></span></div>
now you want to pass that city to the url name?
app.factory('forecast', ['$http', function($http) {
var forecastFactory = {};
forcastFactory.customUrl = function(city){
$http.get('http://api.openweathermap.org/data/2.5/forecast/city?' + city +'q=Warsaw&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
return forecastFactory;
}]);
app.controller('formCtrl', ['forecast', function(Forecast){
$scope.goToUrl = function(name){
var data = Forecast.customUrl(name);
}
}]);
Post a Comment for "How To Send Data From Input To Service?"