创建YouTube AngularJS指令 [英] Create a YouTube AngularJS Directive
问题描述
我创建了以下AngularJS指令嵌入YouTube视频。
I created the following AngularJS directive to embed youtube videos.
// 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>'
};
});
我把它从我的模板&LT; YouTube的code =r1TK_crUbBY&GT;&LT; / YouTube和GT;
我得到了以下错误:
错误:[$插值:noconcat]错误而插值: http://www.youtube.com/embed/ {{code}}
严格的语境不允许转义时,需要一个值得信赖的值,连接多个EX pressions插值。请参见 http://docs.angularjs.org/api/ng 。$ SCE
Error: [$interpolate:noconcat] Error while interpolating: http://www.youtube.com/embed/{{code}} Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required. See http://docs.angularjs.org/api/ng.$sce
我就不能确定哪些是错的{{code}}的前pression的指令。
I can't identify what's wrong with the directive in the {{code}} expression.
推荐答案
通过角1.2,你需要注入 $ SCE
服务和<一个href=\"http://docs.angularjs.org/api/ng.%24sce#methods_trustasresourceurl\"><$c$c>trustAsResourceURL$c$c>在的src
的 IFRAME
。
With Angular 1.2, you need to inject $sce
service and trustAsResourceURL
the src
of an iframe
.
演示:<一href=\"http://plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p=$p$pview\">http://plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p=$p$pview
.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);
}
});
}
};
});
另请参阅:迁移从1.0到1.2 和<一个href=\"http://stackoverflow.com/questions/20045150/angular-js-how-to-set-an-iframe-src-attribute-from-a-variable/20045301#20045301\">related问题。
这篇关于创建YouTube AngularJS指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!