I seem to be stuck while trying to modify a global variable from within an Angular.forEach loop.
I can modify the variable fine, but I can't seem to get that change to apply to the variable when accessed outside of the loop.
I've tried a variety of 'var self = this' and using 'this.addresses = []' throughout the loop to access the array, but that resulted in the same problem. By the time I get to my 'return' statement, my changes are lost.
Here's the code:
$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;
};