I am trying to create a carousel with AngularJS ans UI Bootstrap. Since the carousel in UI bootstrap only supports images, I wan to write my own directive to support youtube video.
I want the video to start to play when the video slide is active, and pause when the slide is not active. Also I would like to pause the carousel lopping when the video is playing. So far i have done the first part but can't pause the carousel because i can't access the pause method of the carousel scope.
My code:
HTML
<div carousel interval="5000">
<div slide ng-repeat="slide in slides" active="slide.active">
<img ng-if="slide.image" ng-src="{{slide.image}}" />
<div ng-if="slide.video" youtube="{{slide.video}}">
</div>
</div>
</div>
JS
.directive('youtube', ['youTubeService', function (youTubeService) {
return {
link: function (scope, element, attrs) {
var player;
var playerReady = false;
var playerState;
var callback;
function createPlayer() {
player = new YT.Player(element[0], {
width: 450,
height: 300,
videoId: attrs.youtube,
events: {
onReady: function (event) {
playerReady = true;
if (callback != null) {
callback();
}
},
onStateChange: function (event) {
playerState = event.data;
if (playerState === YT.PlayerState.PAUSED) {
//scope.$parent.play();
}
}
}
});
}
if (youTubeService.ready) {
createPlayer();
} else {
scope.$on('youTubeServiceReady', function (event, args) {
createPlayer();
});
}
scope.$watch('slide.active', function (active) {
if (active) {
if (playerReady) {
player.playVideo();
//scope.$parent.pause();
} else {
callback = function () {
if (scope.slide.active) {
player.playVideo();
//scope.$parent.pause();
}
}
}
} else if (playerReady && (playerState == YT.PlayerState.BUFFERING || playerState == YT.PlayerState.PLAYING)) {
player.pauseVideo();
}
});
}
};
}]);
Plunk: http://plnkr.co/edit/xCSwsmFisoZA7SQtQuCg
Ui bootstrap carousel code https://github.com/angular-ui/bootstrap/blob/master/src/carousel/carousel.js
Please help, tell me if i'm doing wrong. I'm new to this angularjs framework.Thanks