【问题标题】:Create a YouTube AngularJS Directive创建 YouTube AngularJS 指令
【发布时间】:2013-12-25 05:15:30
【问题描述】:

我创建了以下 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>'
  };
});

当我从模板&lt;youtube code="r1TK_crUbBY"&gt;&lt;/youtube&gt; 调用它时,我收到以下错误:

错误:[$interpolate:noconcat] 插值时出错:http://www.youtube.com/embed/{{code}} 严格的上下文转义不允许在需要可信值时连接多个表达式的插值。见http://docs.angularjs.org/api/ng.$sce

我无法确定{{code}} 表达式中的指令有什么问题。

【问题讨论】:

    标签: javascript angularjs youtube angularjs-directive


    【解决方案1】:

    使用 Angular 1.2,您需要注入 $sce servicetrustAsResourceURLsrciframe

    演示: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);
               }
            });
        }
      };
    });
    

    另请参阅:Migrate from 1.0 to 1.2related question

    【讨论】:

    • 我尝试了上述方法,并在模板末尾添加了缺少的逗号:行,现在它没有给出任何错误,但它没有显示嵌入的视频,检查我看到的元素src 属性为空。
    • @JonathanHindi 它在这里工作:plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p=preview 使用 Angular 1.2 你如何使用模板中的指令?
    • 谢谢现在它可以工作了,我使用的是 我想我需要先将它与当前括号一起传递,然后再通过指令的实际值。但似乎我错了。
    • 您为我节省了很多尝试和错误。谢谢@musically_ut
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    相关资源
    最近更新 更多