【问题标题】:Model not updated in google maps listener - angularjs谷歌地图监听器中未更新模型 - angularjs
【发布时间】:2015-02-11 10:39:01
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs google-maps


    【解决方案1】:

    尝试用 $apply 包装它

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

    扩展名:

    Angular 使用适用于几种异步情况:

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

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

    Extend with a great article

    【讨论】:

    • @BojanaŠekeljić 太棒了!我扩展了我的答案
    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 2018-01-06
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多