Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js not updating dom when expected

Tags:

angularjs

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;
    })
  }
}
like image 789
bjo Avatar asked Feb 22 '13 22:02

bjo


1 Answers

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}
      });
    });
});
like image 139
Josh David Miller Avatar answered Sep 25 '22 08:09

Josh David Miller