javascript 创建 YouTube AngularJS 指令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20447867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:31:22  来源:igfitidea点击:

Create a YouTube AngularJS Directive

javascriptangularjsyoutubeangularjs-directive

提问by Jonathan Hindi

I created the following AngularJS directive to embed youtube videos:

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

When I call it from my template <youtube code="r1TK_crUbBY"></youtube>, I get the following error:

当我从模板调用它时<youtube code="r1TK_crUbBY"></youtube>,出现以下错误:

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

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

I can't identify what's wrong with the directive in the {{code}}expression.

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

回答by musically_ut

With Angular 1.2, you need to inject $sceserviceand trustAsResourceURLthe srcof an iframe.

具有角1.2,你需要注入$sce的服务trustAsResourceURLsrciframe

Demo: http://plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p=preview

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

Also see: Migrate from 1.0 to 1.2and related question.

另请参阅:从 1.0 迁移到 1.2相关问题