如何在 angular 场景中进行此调用?

How to make this call in an angular scenario?

我正在使用名为 YTPlayer 的 YouTube 播放器。 https://github.com/pupunzi/jquery.mb.YTPlayer

在这段代码中,他进行了 JQuery 调用,效果很好。

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

如何在不使用 JQuery 的情况下从我的控制器发出这样的调用?

谢谢。

您创建了一个指令。您可以将指令视为扩展 html。

您的指令将如下所示:

.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

       }
   }
}

然后您将使用此标记将其添加到您的页面:

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

如果您的视频播放器依赖指令,则可以在指令中使用 jQuery。您永远不需要在 angular 控制器中使用 jQuery。如果你发现自己这样做了,那你就不是 "thinking angular".

很多时候,视频播放器和其他组件需要特定的标记才能工作,因此您可以使用模板 属性:

为指令自定义模板
.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

       }
   }
}

这两行:

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

将导致 angular 将 yt-player 标记替换为模板 属性 中的标记。