I am trying to implement a function that triggers when a YouTube video finishes playing. The structure of my code is as follows:
<div class="row">
<div class="col-md-6">
<div id="player" ts-video-player></div>
</div>
</div>
Afterwards, I decided to define a directive like this:
.directive('tsVideoPlayer', ['$state', function ($state) {
// autoplay video
function onPlayerReady(event) {
console.log('autoplay');
event.target.playVideo();
}
// handle video end
function onPlayerStateChange(event) {
if (event.data === 0) {
console.log('finished');
alert('done');
}
}
return {
restrict: 'A',
link: function (scope, element) {
console.log('setting up player');
console.log(element.attr('id'));
function onYouTubePlayerAPIReady() {
console.log('Creating player');
var player = new YT.Player(element.attr('id'), {
height: '390',
width: '640',
videoId: 'GE2BkLqMef4',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}
}
}])
I have included this script in the index.html file:
<script src="http://www.youtube.com/player_api"></script>
However, nothing seems to be happening. My console logs indicate that the 'setting up video player' message and the player id are being displayed, but onYouTubePlayerAPIReady is never triggered.
Can someone provide me with assistance?