brandly / angular-youtube-embed

:tv: Embed a YouTube player with a simple directive

Home Page:http://brandly.github.io/angular-youtube-embed/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to trigger play/pause event in another controller?

Caspert opened this issue · comments

I was wondering how I can get access to the player object, by clicking on a button that is placed in another directory and uses another controller in AngularJS.
So I have a viewController where the video is marked up. On the mainController I have an play button, to start the video, but than the video doesn't start, because it can't find the youtube element.

I used player for the player attribute, like the docs and use the function: player.playVideo();
This is working in the viewController on the same page as the video element, but I would like also have some controls to play pause in the viewController.

I look out for some advice.
Thanks in advance.

in general, if you want to share something between controllers, you need to hold on to that "something" in a service. let's define a simple VideoService like this:

angular.service('VideoService', function () {
  return {
    player: null
  }
})

in the viewController, depend on VideoService and add it to the $scope.

angular.controller('viewController', function ($scope, VideoService) {
  $scope.VideoService = VideoService
})

that way, you can pass VideoService.player into your youtube-video

<youtube-video player="VideoService.player" ...></youtube-video>

in your mainController, you'll want to do something similar

angular.controller('mainController', function ($scope, VideoService) {
  $scope.VideoService = VideoService
})

that way, in your template, you can have a play button

<button ng-click="VideoService.player.playVideo()"></button>

let me know if this doesn't make sense. i didn't actually run this code, and i haven't written any angular lately, so there could very well be many typos here 😄

i'm gonna close this for now. let me know if you have any trouble 🌟