Tules
Tules

Reputation: 4915

Angular directives using video tag for auto loading

This directive controls the video tag by using a linking function to watch the src attribute (which itself is controlled by a binded array with an index of tutorialNumber like this videos[tutorialNumber]) then reloading the video and playing. It also attaches an event listener on 'ended' so that the video automatically loads the next one when it finishes. However scope.tutorialNumber++ does not seem to trigger $watch in the directive upon 'ended' as it does when I trigger it it manually with ng-click events. How can I ensure that the 'ended' event loads the next video as it should?

.directive('videoLoader', function(){
    return function (scope, element, attrs){
        scope.$watch(attrs.videoLoader, function(){
            element[0].load();
            element[0].play()
            video.hasPlayed = true;
            $(video).bind('ended', function(){
                $(this).unbind('ended');
                if (!this.hasPlayed) {
                    return;
                }
                scope.tutorialNumber++;
                scope.loadFromMenu();
            });
        });
    }
});

Upvotes: 2

Views: 2621

Answers (1)

Ben Lesh
Ben Lesh

Reputation: 108501

If you're sure the event is being triggered, try adding a scope.$apply() to your event handler:

.directive('videoLoader', function(){
    return function (scope, element, attrs){
        scope.$watch(attrs.videoLoader, function(){
            element[0].load();
            element[0].play()
            video.hasPlayed = true;
            $(video).bind('ended', function(){
                $(this).unbind('ended');
                if (!this.hasPlayed) {
                    return;
                }
                scope.tutorialNumber++;
                scope.loadFromMenu();
                scope.$apply();
            });
        });
    }
});

Upvotes: 2

Related Questions