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

Include a couple of images to the jQuery Slider

I have a website and am looking to incorporate a jQuery slider that meets my needs. However, the current slider only displays 3 pictures. How can I add one or two additional pictures to the slider? Demo: http://d.lanrentuku.com/down/js/jiaodiantu-883/ He ...

The name variable flickering upon page initialization

As a beginner in Angular, I am currently going through tutorials. However, I am facing an issue where the variable {{ name }} keeps flashing right before the page loads. Has anyone encountered a similar problem? When the page loads, {{ name }} appears for ...

producing base64 encoding that results in a blank image

I have some code that is supposed to get an image from a video using canvas. However, when I save this base64 code into an image, I end up with a black image. What could be causing this issue? Here is my JavaScript code: var input = document.getElementBy ...

Using canvas to smoothly transition an object from one point to another along a curved path

As a beginner in working with canvas, I am facing a challenge of moving an object from one fixed coordinate to another using an arc. While referring to the code example of a solar system on https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutori ...

How to Stop Form from Automatically Submitting in Laravel 5.5 and vue-typeahead's onHit method

I have integrated the vue-typeahead component into my Laravel project using vue-typeahead. However, I am facing an issue where when I select an entry from the result list by pressing the "enter" key, the form automatically submits. Is there a way to preve ...

Encountering issues with React Apollo hooks after integrating React Native into the monorepo system

I am in the process of setting up a React web app and a React-native app within a monorepo using yarn workspaces. The web and controllers are functioning properly, allowing me to successfully execute graphql queries to my apollo-express server. However, up ...

The nonexistence of the ID is paradoxical, even though it is present

I've been working on a school project that involves a dropdown box with the id "idSelect." However, I'm encountering an issue where it says that idSelect is not defined when I try to assign the value of the dropdown box to a variable. Even after ...

When attempting to utilize nsIPrefBranch in a Firefox extension to save data, an unexpected error of NS_ERROR_UNEXPECTED occurs

I am facing a challenge with saving persistent data in a Firefox extension. Currently, I am attempting to utilize nsIPrefBranch in the following manner: var db = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.ns ...

Does the success callback for AJAX operate synchronously?

Understanding that AJAX is asynchronous, a common question arises regarding the event execution within the success callback. Consider this scenario: $.ajax({ url : 'example.com', type: 'GET', success : (dataFromServer) { ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

unable to access the object3D within the current scene

Currently facing an issue where I am unable to retrieve Object3D from the scene, despite the mesh objects being displayed within the scene. Strangely, the scene.children array does not reflect this. Take a look at the screenshot here Here is the code sni ...

Is there a way to automatically create distinct DOM ids every time?

As I delve into coding with JS and the DOM, I frequently encounter the need to create ids (or names) solely for the purpose of grouping DOM elements together (or associating them with each other)1. These ids (or names) are not referenced anywhere else in ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Arranging and Filtering an Object Array Based on their Attributes

Here is an example of a JSON array called items: var items = [ { Id: "c1", config:{ url:"/c1", content: "c1 content", parentId: "p1", parentUrl: "/p1", parentContent: "p1 content", } }, { Id: "c2", ...

Limit the execution speed of a JavaScript function

My JavaScript code is set up to trigger a click event when the user scrolls past a specific element with the class .closemenu. This is meant to open and close a header menu automatically as the user scrolls through the page. The problem I'm facing is ...

Hiding a parent DIV in JS based on specific content: Here's how

I need help figuring out how to hide multiple parent DIVs based on the content of a specific child DIV. Here's an example: <div class="report-per-day"> <div class="report-day">26 May 2022</div> <div class=" ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

A guide on creating a Utility function that retrieves all elements in an array starting from the third element

I've been working on a tool to extract elements from an array starting after the first 2 elements. Although I attempted it this way, I keep getting undefined as the result. // ARRAYS var arr = ['one', 'two', 'three', &a ...

Form validation on the client side: A way to halt form submission

I have a form with several textboxes. The unobtrusive jquery validation is functioning properly and correctly turns the boxes red when invalid values are entered. However, I've noticed that when I click to submit the form, it gets posted back to the s ...