The Angular scope remains stagnant even after applying changes

Having trouble updating a variable in the ng-repeat loop

<div ng-controller="MapViewCtrl">
            <a class="item item-avatar" ng-href="#/event/tabs/mapView" >
                <img src="img/location.jpg"/>
                <span class="input-label">Locations Of event</span>
                <div ng-repeat="item in positions" style="font-size: 12">{{item.address}}</div>
            </a>
        </div>

Code snippet from controller:

$scope.closePage = function() {
        for (var i = 0; i < markers.length; i++) {
            var lng = markers[i].position.A;
            var lat = markers[i].position.k;
            var address = "";
            var latlng = new google.maps.LatLng(lat, lng);
            $scope.$apply( $scope.geocoder.geocode({'latLng': latlng},function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        address = results[0].formatted_address;
                        var location ={
                            address: address
                        }
                        $scope.positions.push(location);
                    }
                }
            }));
        }
        $state.go('eventmenu.createevent');
    };

Looking for suggestions on how to update the 'positions' variable properly.

Answer №1

Instead of simply passing the code, make sure to enclose it in a function and pass that function to $scope.$apply:

$scope.geocoder.geocode({'latLng': latlng},function(results, status) {
    $scope.$apply(function(){
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                address = results[0].formatted_address;
                var location = {
                    address: address
                }
                $scope.positions.push(location);
            }
        }
    })
});

It's important to call apply within the callback from the geocoder. This notifies Angular to watch for any scope changes.

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

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

"Automating the process of toggling the edit mode of a contenteditable element – how is

Is there a specific event I can use to programmatically start or stop editing a contenteditable element, similar to when the user focuses or blurs it? I have tried using .focus(), .click(), and even setting the selection to its content, but none of them se ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

Problems with Ajax calls are preventing Internet Explorer9 and Internet Explorer10 from functioning properly

I am facing an issue with displaying item pages using Ajax. The function works perfectly in Chrome, but not in Internet Explorer. <script type="text/javascript"> function obtainInfo(str) { if (str=="") { document. ...

transfer an image file to a php script using ajax

Having just started, my goal is to upload an image and send it to a server for insertion into a database. Initially, all I want to do is echo the file name that I will be sending. However, I am encountering issues with this process, as I keep receiving noi ...

How can I add a channel to a category using await(discord.js)?

Having trouble organizing a new channel within a category. The .setParent(categoryID) method seems to only work with existing channels, causing an issue when I attempt to execute my code. Take a look at the code snippet below: client.on("message" ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...

Express not automatically displaying the index.html file as a static file

In the structure of my directory, I have: build/ (contains gulp tasks for generating dist from src) dist/ (this is the static app that is being served) (all other assets, css, images, etc) index-5c1755df65.html src/ (source files that cannot be serv ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

What is the most effective way to reset the v-model in the child component using the parent component?

Could you please assist me? I have been trying for 10 hours straight and it doesn't seem to work. What I am aiming for is that when I click on @click="cleanDataForm" in the Parent Component, the v-model text in the Child component will be emptied. I h ...

Steps for running a TypeScript project as a child process within a JavaScript project

I am facing an issue with integrating my Electron app, written mainly in JavaScript, with an Express server project built in TypeScript. When I attempt to create a child process of the TypeScript project within my electron.js file, I encounter TypeScript e ...

What could be causing the Material AngularJS (CSS) on my website to not function properly, unlike the demo that was

I am completely new to AngularJS and I want to incorporate the material design version of AngularJS for developing a form. I followed the beginner's guide and attempted to create something, but it didn't turn out like the one on the website. So, ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

Modify the button's color based on a separate column within the table

Currently, I am implementing Datatables along with X-editable and including some bootstrap buttons within a table. My objective is to change the color of the button in the 'Validated' column to green when the user updates the editable 'Statu ...

Is it possible that $watch does not function properly for instantaneous statements?

Are you tired of hearing the same old story? Well, I'm here to bring something new to the table. You see, I'm a novice in the world of bla bla... Recently, I've encountered a perplexing situation with my code. In the snippet below, whenever ...

Encounter issue when using GAS withSuccessHandler function

I've developed a Google Sheets add-on that utilizes a modal dialog for the user interface. I encountered an issue with the success handler not running as expected, so I created a basic test interface to troubleshoot the problem. After the server-side ...

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...