【问题标题】:AngularJS $location doesn't work with google.maps.event listenerAngularJS $location 不适用于 google.maps.event 监听器
【发布时间】:2015-03-26 19:57:02
【问题描述】:

我在 angularJS 控制器中初始化了一个谷歌地图,并为地图事件添加了一个监听器

google.maps.event.addListener(map, 'dragend', MapMoveAround);
......
function MapMoveAround() {
    console.log($location.url());
    $location.path('/other_path');
    console.log($location.url());
}

当我触发谷歌地图事件时,控制台显示 url 已更改,但我停留在旧页面。如果我将 $location.path('/other_path') 更改为

window.location.replace('/#/other_path')

它将进入新页面,但“返回”按钮不起作用。

谁能提供一个 AngularJS 解决方案?

【问题讨论】:

  • 您需要使用$scope.$apply() 才能运行摘要循环

标签: javascript angularjs google-maps


【解决方案1】:

通过事件运行 Angular 代码不会运行摘要循环,在这种情况下,您需要使用 $scope.$apply() 手动运行它,以便您的 $location 更改生效。

代码

google.maps.event.addListener(map, 'dragend', MapMoveAround);
......
function MapMoveAround() {
    console.log($location.url());
    $scope.$apply(function(){
      $location.path('/other_path');
    })
    console.log($location.url());
}

【讨论】:

    【解决方案2】:

    以下代码也适用于...

     google.maps.event.addListener(map, 'dragend', MapMoveAround);
    ......
    function MapMoveAround() {
      console.log($location.url());
      $timeout(function() {
        $location.path('/other_path');
      }, 500)
      console.log($location.url());
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多