Saturday, 28 September 2013

AngularJS - Help creating a YouTube frameapi directive

AngularJS - Help creating a YouTube frameapi directive

I am trying to build a yotube directive with the Youtube Player FrameAPI
example code
Here is the code
HTML
<div you-tube id="player"></div>
Directive
angular.module('mainApp.player').directive('youTube',
function(/*slides_ui*/) {
return {
restrict: 'A', // only activate on element attribute
scope: true, // New scope to use but rest inherit from parent
controller: function($scope, $element, $attrs) {
}, //open for now
link: function(scope, elm, attrs, ctrl) {
// Load the js api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
});
Now the problem I am facing is where to put the rest of the frameapi js.
FrameAPI js
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
If I leave the above code in the HTML it works.
If I move it in the Controller/link function of the directive it doesn't
work.
What am I missing?

No comments:

Post a Comment