Angular js在预期时不会更新dom

bjo*_*bjo 7 angularjs

我有一个小提琴,但基本上它正在做什么地理编码输入到文本框的地址.输入地址并按下"enter"后,dom不会立即更新,而是等待文本框的其他更改.如何在提交后立即更新表格?我对Angular很新,但我正在学习.我发现它很有趣,但我必须学会以不同的方式思考.

这是小提琴和我的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;
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ler 21

您的问题是该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}
      });
    });
});
Run Code Online (Sandbox Code Playgroud)