0
我似乎在嘗試修改Angular.forEach循環內的全局變量時被卡住了。無法更新angular.forEach循環中的全局變量
我可以修改變量的罰款,但我似乎無法得到該變化適用於變量時訪問的循環之外。
我已經嘗試了各種'var self = this',並在整個循環中使用'this.addresses = []'來訪問數組,但導致了同樣的問題。當我得到我的「回報」聲明時,我的變化就失去了。
下面的代碼:
$scope.getLocation = function(val) {
var geocoderRequest = {
address: String(val),
componentRestrictions: {
'country': 'US'
}
};
var addresses = [1]; // **** shows addresses as [1] *****
geocoder.geocode(geocoderRequest, function(callbackResult) {
console.log('address in geocode: ' + addresses); // ***** shows addresses as [1] ****
var f = '';
angular.forEach(callbackResult.results, function(item) {
console.log('address in angular: ' + addresses); // **** shows addresses as [1] *****
if (item.types[0] == 'locality') {
for (f = 1; f < item.address_components.length; f++) {
if (item.address_components[f].types[0] ==
"administrative_area_level_1") {
addresses.push(item.address_components[0].short_name + ', ' + item.address_components[
f].short_name);
console.log('addresses in each: ' + addresses); // **** shows addresses as [1, 2, 3] after I 'push' 2 and 3 into addresses array ****
break;
}
}
}
});
});
console.log('addresses outside: ' + addresses); // ***** shows addresses as [1] even after pushing 2 and 3 *****
return addresses;
};
您需要使用回調函數中的AJAX調用的結果來完成所有工作。有關詳細信息,請參閱[此問題](http://stackoverflow.com/q/14220321/497356)。 – 2014-09-24 00:35:25
有太多這樣的類似問題,請檢查[this](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)和[this]( http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – PSL 2014-09-24 00:35:59
查看https://docs.angularjs.org/api/ng/service/$q – Phil 2014-09-24 01:04:13