创建 YouTube AngularJS 指令 [英] Create a YouTube AngularJS Directive

查看:27
本文介绍了创建 YouTube AngularJS 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下 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 iframesrc.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆