创建 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>'
};
});
当我从我的模板 <youtube code="r1TK_crUbBY"></youtube>
调用它时,我收到以下错误:
When I call it from my template <youtube code="r1TK_crUbBY"></youtube>
, I get the following error:
错误:[$interpolate:noconcat] 插值时出错:http://www.youtube.com/embed/{{code}}严格上下文转义不允许在需要可信值时连接多个表达式的插值.参见 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}}
表达式中的指令有什么问题.
I can't identify what's wrong with the directive in the {{code}}
expression.
推荐答案
使用 Angular 1.2,你需要注入 $sce
服务 和 trustAsResourceURL
iframe
的 src
.
With Angular 1.2, you need to inject $sce
service and trustAsResourceURL
the src
of an 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);
}
});
}
};
});
另见:从 1.0 迁移到1.2 和 相关问题.
这篇关于创建 YouTube AngularJS 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!