I've encountered a challenge while attempting to modify a global variable within an Angular.forEach loop.
Although I can successfully update the variable within the loop, I'm struggling to maintain those changes when accessing the variable outside of the loop.
I experimented with different approaches such as 'var self = this' and using 'this.addresses = []' throughout the loop to interact with the array. However, all my efforts led to the same issue - by the time I reached the 'return' statement, my modifications were lost.
The following is the snippet of code in question:
$scope.getLocation = function(val) {
var geocoderRequest = {
address: String(val),
componentRestrictions: {
'country': 'US'
}
};
var addresses = [1]; // **** displays addresses as [1] *****
geocoder.geocode(geocoderRequest, function(callbackResult) {
console.log('address in geocode: ' + addresses); // ***** displays addresses as [1] ****
var f = '';
angular.forEach(callbackResult.results, function(item) {
console.log('address in angular: ' + addresses); // **** displays 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); // **** displays addresses as [1, 2, 3] after pushing 2 and 3 into addresses array ****
break;
}
}
}
});
});
console.log('addresses outside: ' + addresses); // ***** still shows addresses as [1] even after adding 2 and 3 *****
return addresses;
};