2013-02-22 57 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