Angular js does not update dom when expected

I have a fiddle for this, but basically what it does is geocoding the address that is entered into the text box. After entering the address and pressing 'enter', dom is not immediately updated, but waits for another change in the text box. How do I get it to update the table immediately after sending? I am very new to Angular, but I am learning. This is interesting to me, but I must 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; }) } } 
+6
source share
1 answer

Your problem is that the geocode function is asynchronous and therefore updated outside of the AngularJS digest loop. You can fix this by wrapping a callback function when calling $scope.$apply , which allows AngularJS to know how to start the digest because the 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} }); }); }); 
+18
source

All Articles