我正在使用名为YTPlayer的youtube播放器。 https://github.com/pupunzi/jquery.mb.YTPlayer
在这段代码中,他做了一个JQuery调用,工作正常。
$(document).ready(function () {
$(".player").mb_YTPlayer();
});
如何在不使用JQuery的情况下从我的控制器进行这样的调用?
感谢。
答案 0 :(得分:1)
您创建了一个指令。您可以将指令视为扩展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是可以的。你永远不需要在角度控制器中使用jQuery。如果你发现自己这样做了,那你就不会思考角度&#34;。
很多时候,视频播放器和其他组件需要特定的标记才能工作,因此您可以使用模板属性自定义指令的模板:
.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标记。