2013-02-22 53 views
6

我对此有一个小提琴,但基本上它是在做什么它对输入到文本框的地址进行地理编码。输入地址并按下'enter'后,dom不会立即更新,而是等待文本框的另一个更改。如何在提交后立即更新表格? 我对Angular很陌生,但我在学习。我觉得很有趣,但我必须学会以不同的方式思考。Angular js没有在预期时更新dom

这里是小提琴和我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; 
    }) 
    } 
} 

回答

18

你的问题是,geocode功能是AngularJS之外异步的,因此更新周期消化。您可以通过在呼叫包裹你的回调函数解决这个问题,以$scope.$apply,它可以让AngularJS知道跑摘要因为东西已经改变了:

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} 
     }); 
    }); 
}); 
+0

谢谢,正是我需要的。学到了新东西。 – bjo 2013-02-22 23:09:48

+0

嗨,我有完全相同的问题,但我试图做一个指令和$范围内$ apply不适合我在那里工作。我不知道我是否错过了一些东西。请帮忙。 – Rober 2013-11-20 19:07:07

+0

@Rober你可以发布一个Plunker吗? – 2013-11-20 19:22:15