如何在 AngularJS $http 中的 url 中添加变量元素



我有以下代码来提取天气预报。如何将 url 中的邮政编码设置为变量。我已经在简单的 javascript 中完成了此操作,方法是将 url 分解为子字符串,然后在 get 方法中传递,但这在 AngularJS 中不起作用。请帮忙。

JS代码

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;
});
};
};

索引.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>

您需要向 weatherCtrl 函数添加一个参数,并将其添加到 URL 的变量中。然后使用参数调用函数。

JS代码

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;
});
};
};

索引.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 的答案是正确的。 如果您从某个地方收到 URL,并且必须解析它并提取邮政编码,则可以使用正则表达式匹配

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

是网址字符串。

最新更新