模型未在谷歌地图监听器中更新 - angularjs

Boj*_*jić 1 javascript google-maps angularjs

我有一个函数,$scope.addReport()应该执行以下操作:

  • 单击时添加事件侦听器以添加新标记(通过执行placeMarker(location))
  • $scope.TempMarker使用新坐标更新模型
  • 显示具有ng-show="showForm'指令的表格
  • 删除侦听器,因此只能放置一个标记

我遇到的麻烦是,如果我尝试$scope.showForm在侦听器内进行更改,它不会更新范围,它仅在侦听器中计算为true.如果我将其移出侦听器,则会更新范围并显示表单.

所以我的问题是为什么范围没有更新$scope.showForm但它正在更新$scope.TempMarker,我如何在监听器中更新?

这是代码:

//attached to ng-show directive 
$scope.showForm = false;

//this function creates a marker based on passed location
function placeMarker(location) {
      $scope.tempMarker = new google.maps.Marker({
          position: location, 
          map: $scope.map,
          draggable: true
      });
  }

//this is executed on addReport() click
$scope.addReport = function() {
  //$scope.showForm = !$scope.showForm; ---> if declaration is here, scope is updated and the form is shown
  var newMarkerListener = google.maps.event.addListener($scope.map, 'click', function(event) {
      placeMarker(event.latLng); // create the actual marker

      //update the new report object
      $scope.newReport.lat = event.latLng.lat();
      $scope.newReport.lng = event.latLng.lng();
      $scope.showForm = !$scope.showForm; // -----> not updating the scope
      console.log($scope.showForm) // logs true
      google.maps.event.addListener($scope.tempMarker,'dragend',function(event) {
          $scope.newReport.lat = event.latLng.lat();
          $scope.newReport.lng = event.latLng.lng();
      });

     google.maps.event.removeListener(newMarkerListener);
    });
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ant 6

尝试用$ apply包装它

$scope.$apply(function () { 
   $scope.showForm = !$scope.showForm; 
});
Run Code Online (Sandbox Code Playgroud)

延期:

Angular用法适用于几个异步情况:

  1. 活动(ng-click等)
  2. Ajax调用
  3. 超时

当使用非平凡的异步操作时,绑定将不会在赋值后自动发生,因此最好使用$ apply.

延伸一篇很棒的文章