7

I have a fiddle for this, but basically what it's doing it geo-encoding an address that is input into a textbox. After the address is entered and 'enter' is pressed, the dom does not immediately update, but waits for another change to the textbox. How do I get it to update the table right after a submit? I'm very new to Angular, but I'm learning. I find it interesting, but I have to learn to think differently.

Here is the fiddle and my controller.js

http://jsfiddle.net/fPBAD/

var myApp = angular.module('geo-encode', []);

function FirstAppCtrl($scope, $http) {
  $scope.locations = [];
  $scope.text = '';
  $scope.nextId = 0;

  var geo = new google.maps.Geocoder();

  $scope.add = function() {
    if (this.text) {

    geo.geocode(
        { address : this.text, 
          region: 'no' 
        }, function(results, status){
          var address = results[0].formatted_address;
          var latitude = results[0].geometry.location.hb;
          var longitude = results[0].geometry.location.ib;

          $scope.locations.push({"name":address, id: $scope.nextId++,"coords":{"lat":latitude,"long":longitude}});
    });

      this.text = '';
    }
  }

  $scope.remove = function(index) {
    $scope.locations = $scope.locations.filter(function(location){
      return location.id != index;
    })
  }
}

1 Answer 1

21

Your problem is that the geocode function is asynchronous and therefore updates outside of the AngularJS digest cycle. You can fix this by wrapping your callback function in a call to $scope.$apply, which lets AngularJS know to run a digest because stuff has changed:

geo.geocode(
  { address : this.text, 
    region: 'no' 
  }, function(results, status) {
    $scope.$apply( function () {
      var address = results[0].formatted_address;
      var latitude = results[0].geometry.location.hb;
      var longitude = results[0].geometry.location.ib;

      $scope.locations.push({
        "name":address, id: $scope.nextId++,
        "coords":{"lat":latitude,"long":longitude}
      });
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, just what I needed. Learned something new.
Hi, I have exactly same problem, but I´m trying to do it inside a directive and $scope.$apply is not working for me there. I don´t know if I´m missing something. Please help.
@Rober Can you post a Plunker?
@JoshDavidMiller: There you go... plnkr.co/edit/QRj6jXQYxSRR3CseavQY?p=preview . As you can see the geocode is executed after the center and the map are created. That´s why the marker is in the right point, but the center is not there but in Getafe (another city).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.