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

标签 javascript angularjs google-maps

我有一个函数 $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);
    });
}

最佳答案

尝试用 $apply 包装它

$scope.$apply(function () { 
   $scope.showForm = !$scope.showForm; 
});

扩展名:

Angular 的使用适用于多种异步情况:

  1. 事件(ng-click 等)
  2. Ajax 调用
  3. 超时

当使用非平凡的异步操作时,绑定(bind)不会在分配后自动发生,因此最好使用 $apply。

Extend with a great article

关于javascript - 模型未在谷歌地图监听器中更新 - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28452166/

相关文章:

javascript - 如何测试圆是否在旋转的对象中

javascript - 单击 anchor 而不是新窗口打开弹出窗口

javascript - 如何在类外访问 Aurelia EventAggregator?

javascript - AngularJS 模块

angularjs - 如何让 Angular js 在过滤器中隐藏 DOM 元素,而不是删除它们

javascript - 为什么当使用 google-maps v3 上的 MVCObject 更改缩放时我的代码无法提醒 map 的缩放

android - 谷歌地图代码不适用于 android - 没有 map

javascript - 如何在预先存在的折线上放置标记?

javascript - 禁用 "remove on backspace"(或完全删除 ibeam)

javascript - ng-class 在一个 ng-class 指令中具有条件和函数