我使用指令在我的模板中插入youtube播放器,
app.directive('youtube', function($window, youTubeApiService) {
return {
restrict: "E",
scope: {
videoid: "@"
},
template: '<div></div>',
link: function(scope, element, attrs, $rootScope) {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
youTubeApiService.onReady(function() {
player = setupPlayer(scope, element);
});
function setupPlayer(scope, element) {
return new YT.Player(element.children()[0], {
playerVars: {
autoplay: 0,
html5: 1,
theme: "light",
modesbranding: 0,
color: "white",
iv_load_policy: 3,
showinfo: 1,
controls: 1
},
videoId: scope.videoid,
});
}
scope.$watch('videoid', function(newValue, oldValue) {
if (newValue == oldValue) {
return;
}
Player.cueVideoById(scope.videoid);
});
}
};
});
我的HTML看起来像这样,
<div class="container-info">
<ul class="trailers">
<li><a href="#">ePbKGoIGAXY</a></li>
<li><a href="#">KlyknsTJk0w</a></li>
<li><a href="#">nyc6RJEEe0U</a></li>
<li><a href="#">zSWdZVtXT7E</a></li>
<li><a href="#">Lm8p5rlrSkY</a></li>
</ul>
<div class="container-trailers">
<youtube videoid="ePbKGoIGAXY"></youtube>
</div>
</div>
我想要做的是点击其中一个链接,然后更改videoid
的值,以便呈现不同的YouTube链接。
<div class="container-info">
<ul class="trailers">
<li><a href="#">ePbKGoIGAXY</a></li>
<li><a href="#">KlyknsTJk0w</a></li>
<li><a href="#">nyc6RJEEe0U</a></li>
<li><a href="#">zSWdZVtXT7E</a></li> <-- clicked element
<li><a href="#">Lm8p5rlrSkY</a></li>
</ul>
<div class="container-trailers">
<youtube videoid="zSWdZVtXT7E"></youtube> <-- new youtube link
</div>
</div>
答案 0 :(得分:1)
您可以使用$watch
和ng-click
:
HTML:
<div ng-app="app">
<div class="container-info">
<ul class="trailers">
<li><a href="#" ng-click="videoid = 'ePbKGoIGAXY'">ePbKGoIGAXY</a></li>
<li><a href="#" ng-click="videoid = 'KlyknsTJk0w'">KlyknsTJk0w</a></li>
</ul>
<div class="container-trailers">
<youtube videoid="videoid"></youtube>
</div>
</div>
</div>
JS:
var app = angular.module("app", []);
app.directive('youtube', function($window) {
return {
restrict: "E",
scope: {
videoid: "="
},
template: '<div></div>',
link: function(scope, element, attrs, $rootScope) {
scope.$watch('videoid', function (newVal, oldVal) {
console.log(newVal);
});
}
};
});