-1

I have the below code to pull the weather forecast. How do I make the zip code within the url as variable. I have done this in simple javascript by breaking down the url to substrings and then passing then in the get method but that is not working in AngularJS. Please help.

JS code

controllers.weatherCtrl= function ($scope,$http) {
$scope.getWeather=function() {
  $http.get('http://api.openweathermap.org/data/2.5/forecast?zip=60007&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
  .then(function(response){
    $scope.weatherdata=response.data;
    });
  };
};

Index.html

<div class="container border">

      <input ng-model="zip">
      <button class="btn" ng-click="getWeather()">Get Weather</button>
      <br>
      <span>{{weatherdata.city.name + ', ' + weatherdata.city.country}}</span>
    </div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ABD
  • 49
  • 8
  • Possible duplicate of [AngularJS passing data to $http.get request](https://stackoverflow.com/questions/13760070/angularjs-passing-data-to-http-get-request) – Stanislav Kvitash Jun 11 '18 at 15:16

2 Answers2

1

You would need to add in a parameter to the weatherCtrl function and add that to variable to the URL. Then you call the function with the parameter.

JS code

controllers.weatherCtrl= function ($scope,$http) {
$scope.getWeather=function(zipcode) {
  $http.get('http://api.openweathermap.org/data/2.5/forecast?zip='+zipcode+'&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
  .then(function(response){
    $scope.weatherdata=response.data;
    });
  };
};

Index.html

<div class="container border">

      <input ng-model="zip">
      <button class="btn" ng-click="getWeather(zip)">Get Weather</button>
      <br>
      <span>{{weatherdata.city.name + ', ' + weatherdata.city.country}}</span>
    </div>
Mark S.
  • 3,849
  • 4
  • 20
  • 22
  • Thanks Mark. That helped! I also figured that adding + $scope.zip + would directly bind it to the input in the HTML. – ABD Jun 11 '18 at 16:45
0

If you create the url, then Mark S's answer is the correct one. if you receive the url from somewhere and you have to parse it and extract the zip code, you can use a regex match

url.match(/(?<=zip\=)\d*(?=\&)/g)

being url the url string.

Leandro
  • 180
  • 4