Angularjs 为什么指令在页面更改后不起作用?有棱角的
我在一个页面上有一个简单的youtube指令,效果很好。但是,如果我转到第2页,然后返回,该玩家将不再出现。 我是否遗漏了什么,或者我只是误解了指令的工作原理 这是你的电话号码 指示Angularjs 为什么指令在页面更改后不起作用?有棱角的,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我在一个页面上有一个简单的youtube指令,效果很好。但是,如果我转到第2页,然后返回,该玩家将不再出现。 我是否遗漏了什么,或者我只是误解了指令的工作原理 这是你的电话号码 指示 app.directive('youtube', function($window) { return { restrict: "E", template: '<div></div>', link: function(scope, element, attrs
app.directive('youtube', function($window) {
return {
restrict: "E",
template: '<div></div>',
link: function(scope, element, attrs) {
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;
$window.onYouTubeIframeAPIReady = function() {
player = new YT.Player(element.children()[0], {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
};
},
}
});
谢谢 每次实例化
youtube
指令时,您都会将youtube脚本注入页面,然后根据onyoutubeiframeapiredy
事件实例化播放器
这意味着第二次实例化该指令时,onyoutubeiframeapiredy
从不激发(因为该API从第一次开始就已就位)
避免这种情况的一种方法是让youtube
指令的link函数检查是否已经注入了youtube API,如果已经注入,则重新使用它:
if (window.YT) {
player = new YT.Player(element.children()[0], {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
} else {
// your existing code here
}
(或者,您可以直接将youtube API作为普通的
标记嵌入index.html中,而不是通过javascript将其作为指令的一部分注入,因此它可以用于任何需要使用它的指令)。使用它,您会很好。非常感谢。这正是我所需要的。干杯,乐意帮忙!
if (window.YT) {
player = new YT.Player(element.children()[0], {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
} else {
// your existing code here
}