Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem with a sending data form input to the service. For example I have an input:

<input type="text" class="form-control" placeholder="City name...">
<span class="input-group-btn">
      <button class="btn btn-default" type="button">Go!</button>
</span>

And a service which is geting data for rest api:

app.factory('forecast', ['$http', function($http) { 
  return $http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo') 
            .success(function(data) { 
              return data; 
            }) 
            .error(function(err) { 
              return err; 
            }); 
}]);

How can I send the city name from the input after clicking button "Go" to construct my own api link ? And then display those data in view ? I mean something like this http://api.openweathermap.org/data/2.5/forecast/city?q=VALUE_FROM_THE_INPUT&units=metric&mo

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
147 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should assign your input an ng-model directive, like this:

<input type="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'); 
       }
   };
}]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...