AngularJS 的 `$location.path()` 在我点击浏览器的 BACK 按钮时没有改变?

AngularJS's `$location.path()` is not changed when I click BACK button of browser?

我正在使用 videoJS 动态加载视频,并希望在 routelocation 更改时销毁视频播放器,我尝试将其包装在这样的指令中(Coffeescript 代码):

angular.module('myModule')
.directive('myDirective', ($location)->
  return {
  restrict: 'A'
  scope: {rawUrl: '='}
  link: (scope, element, attrs) ->    
    attrs.type = 'application/x-mpegURL'
    setup =
      controls: true
      preload: 'auto'
      autoplay: true
      height: window.innerHeight
      width: window.innerWidth
      'data-setup': '{example_option: true}'

    myPlayer = element

    scope.$watch('location.path()', ->
      # TODO: destroy videoJS when user leaves video page
      console.log($location.path())
      if not $location.path().match '/video/'
        console.log("destroy you!")
        videojs(attrs.id).dispose()

    )
    scope.$watch('rawUrl.videoUrl', (newvalue)->
      if newvalue
        player = videojs(attrs.id, setup, ->
          console.log('created')
          this.src(newvalue)
          return
        )
        videojs(attrs.id).ready( ->
          console.log('ready!')
          myPlayer = this
          aspectRatio = 9 / 16;
          resizeVideoJS = ->
            myPlayer.width(window.innerWidth).height(window.innerHeight);            )


   )
  }
)

但是,我发现如果我使用浏览器的返回按钮更改页面,scope.$watch('location.path(), mycallback) 中的回调函数不会被调用..

有人对此有想法吗?谢谢!

我不是 100% 确定这会起作用,但您可以尝试将 $location.path() 调用包装在范围内定义的函数中,例如

scope.location = { path : function () { return $location.path(); } }

同样,我不确定路由更改是否会在摘要周期之前发生。

如果是,您可以改为使用以下方法侦听位置更改事件 (Angular doc on $location events):

scope.$on('$locationChangeStart', function (event) { /* code you had in your watcher should still work fine here */ });

编辑: 将 $route 事件编辑为 $location 事件(参考文档中的新 link 和 this answer。$location 事件应在浏览器的变化url。

只需使用scope.$on('$destroy', destroyCallback)