Search code examples
angularjsytplayer

How to make this call in an angular scenario?


I'm using a youtube player called YTPlayer. https://github.com/pupunzi/jquery.mb.YTPlayer

In this code he makes a JQuery call which works fine.

$(document).ready(function () {
    $(".player").mb_YTPlayer();
});

How can i make such a call from my controller without using JQuery?

Thanks.


Solution

  • You create a directive. You can think of directives as extending html.

    Your directive will look something like this:

    .directive('ytPlayer', function() {
       return {
           scope: {
               pathToVideo: '&'
           },
           link(scope, element, attr) {
                //at this point, the DOM is ready and the element has been added to the page.  It's safe to call mb_YTPlayer() here.
                //also, element is already a jQuery object, so you don't need to wrap it in $()
                element.mb_YTPlayer();
    
                //scope.pathToVideo() will return '/video.mpg' here
    
           }
       }
    }
    

    And you'll add it to your page with this markup:

    <yt-player path-to-video="/video.mpg"></yt-player>
    

    It's OK to use jQuery inside of a directive if your video player is dependent on it. You should never need to use jQuery in an angular controller. If you find yourself doing so, you're not "thinking angular".

    Many times, video players and other components require specific markup to work, so you can customize your template for the directive with the template property:

    .directive('ytPlayer', function() {
       return {
           scope: {
               pathToVideo: '&'
           },
           replace: true,
           template: '<div><span></span></div>'
           link(scope, element, attr) {
    
                element.mb_YTPlayer();
    
                //scope.pathToVideo() will return '/video.mpg' here
    
           }
       }
    }
    

    These two lines:

    replace: true,
    template: '<div><span></span></div>'
    

    will cause angular to replace the yt-player markup with the markup in the template property.