0

I was using videoJS to load video dynamically, and want to destroy the video player when route or location changes, I tried to wrap it in a directive like this (Coffeescript code):

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);            )


   )
  }
)

However, I found the callback function within scope.$watch('location.path(), mycallback) is not called if I changed the page using broswer's BACK button..

Does anyone have ideas about this? Thanks!

enter image description here

2 Answers 2

1

Just use scope.$on('$destroy', destroyCallback)

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not 100% sure this will work, but you could try to wrap the $location.path() call inside of a function defined on the scope e.g.

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

Again, I'm not sure if the route change will occur prior to the digest cycle.

If it does, you could, instead, listen for the location-change event (Angular doc on $location events) using:

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

Edit: Editing $route events to $location events (refer to new link in documentation and this answer. $location events should be broadcasted upon changes in the browser's url.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.