Unable to alter a global variable while iterating through an angular.forEach loop

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;

};

Answer №1

To tackle the issue, the ultimate solution involved leveraging Angular's $q to deliver a promise:

Inside the controller:

.controller('LaunchformController', 
['$scope', '$q', 'geocoder', function ($scope, $q, geocoder) {

  $scope.getLocation = function(val) {      
    var deferred = $q.defer();      

    geocoder.geocode({ address: String(val), componentRestrictions: {'country':'US'} }, 
      function(callbackResult) {        
        deferred.resolve(callbackResult);
    });

    return deferred.promise;            
  };
}])

Within the service:

.service('geocoder',function() {
    this.geocode=function(georequest, outerCallback) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode( georequest, function(results, status) {        
        if (status == google.maps.GeocoderStatus.OK) {          
          var f = '';                  
          var addresses = [];
          angular.forEach(results, function(item){  
            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);            
                break;
                }
              }
            }            
          });
          outerCallback(addresses);         
        } else {
          outerCallback({success:false, err: new Error('Geocode was not successful for the following reason: ' + status), results: null});
        }
      });
    };
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

refreshing the webpage's content following the completion of an asynchronous request

I am working on an Ionic2 app that utilizes the SideMenu template. On the rootPage, I have the following code: export class HomePage { products: any = []; constructor(public navCtrl: NavController, public navParams: NavParams, private woo: WooCommer ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

What are the advantages of choosing Express over AngularJS?

It's clear to me that Express is typically found on the server, while Angular is usually on the client side. However, from what I've gathered, Angular has the capability to perform all the functions that Express can, such as: routing interactin ...

Resource loading error: The server returned a 404 (Not Found) status code, as shown in the console

Click here I have a simple file structure where index.html, script.js, and login.js are all in the same root folder without any subfolders. The issue I'm facing is that although the connection to the database works fine, there seems to be a problem wi ...

Change the font awesome class when the button is clicked

Here is the code I have in this jsfiddle. I am trying to change the font awesome icon on button click using javascript, but it doesn't seem to be working. I am new to javascript, so please pardon me if this is a silly question. HTML <button id="f ...

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

Personalized Svelte interface Slider tag

I am trying to customize the label of a smui/slider in a tick marks and discrete slider. While I found instructions on how to do this using material web components at https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc- ...

Is it possible to identify a legitimate JSONP response?

My goal is to exchange data with a web service on a separate server that lacks CORS support. I am required to utilize JSONP for this purpose. The service mandates authentication, and when the user is in an SSO environment, they are seamlessly passed throug ...

Can javascript be used to swap out the folder in my URL?

I have been searching for solutions on how to change the language of my website using jQuery, but so far I have not found anything that works for me. Let's take my website as an example: www.domain.com I have separate folders for different languages. ...

Adjust the hue as you scroll

I've been searching for a solution to this issue, but I haven't been able to make it work. My goal is to have the page header change from a transparent background to a red background as the user starts scrolling down the page. $(window).on("s ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

I would like to add a border at the bottom of each item in a ul list

My current focus is on making my website responsive with a breakpoint set at 576px I am aiming to achieve the design shown in this image without any space in the border-bottom and have both elements expand to full width: menu li hover However, I'm c ...

The value of req.headers('Authorization') has not been defined

I'm experiencing difficulty with my code as the token is coming back as undefined. Here is the frontend section: export const fetchUser = async (token: any) => { const res = await axios.post('/user/getuser', { headers ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

Code that changes every occurrence of a particular filtered selection of HREF values to a different value

When faced with the limitation in Firefox where links cannot be opened in a new tab if they have a HREF tag diverting to a function, it might be necessary to utilize a script to convert them to an actual HREF. Understanding the functionality of foo: func ...

Explore the comparison feature with jQuery's combobox

I am attempting to compare values from an array with values in a combobox using jQuery, but I am encountering difficulties. My array is structured like this: (value 1, value 2,...) names separated by commas (Example: john smith, peter pan). On the other h ...

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

looking to display the latest status value in a separate component

I am interested in monitoring when a mutation is called and updates a status. I have created a component that displays the count of database table rows when an API call is made. Below is the store I have implemented: const state = { opportunity: "" } ...

Are there any alternatives to jQuery address in the realm of dojo?

Currently, I am working on developing an ajax application using dojo. I am curious if there is a feature comparable to jQuery Address in terms of functionality. My goal is to implement ajax-based hash url navigation similar to Twitter and Facebook using do ...