Jon*_*ndi 12 javascript youtube angularjs angularjs-directive
我创建了以下AngularJS指令来嵌入youtube视频:
// A Simple youtube embed directive
.directive('youtube', function() {
return {
restrict: 'EA',
scope: { code:'=' },
replace: true,
template: '<div style="height:400px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="http://www.youtube.com/embed/{{code}}" frameborder="0" allowfullscreen></iframe>'
};
});
Run Code Online (Sandbox Code Playgroud)
当我从模板中调用它时<youtube code="r1TK_crUbBY"></youtube>,出现以下错误:
错误:[$ interpolate:noconcat]插值时出错:http://www.youtube.com/embed/ {{code}} Strict Contextual Escaping禁止在需要可信值时连接多个表达式的插值.见http://docs.angularjs.org/api/ng.$ sce
我无法确定{{code}}表达式中的指令有什么问题.
mus*_*_ut 32
具有角1.2,你需要注入$sce的服务和trustAsResourceURL对src的iframe.
演示:http://plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p = preview
.directive('youtube', function($sce) {
return {
restrict: 'EA',
scope: { code:'=' },
replace: true,
template: '<div style="height:400px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="{{url}}" frameborder="0" allowfullscreen></iframe></div>',
link: function (scope) {
scope.$watch('code', function (newVal) {
if (newVal) {
scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal);
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
另请参阅:从1.0迁移到1.2以及相关问题.