javascript - 创建 YouTube AngularJS 指令

标签 javascript angularjs youtube angularjs-directive

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

当我从我的模板中调用它时 <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

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

最佳答案

使用 Angular 1.2,你需要注入(inject) $sce servicetrustAsResourceURL iframesrc

演示: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 .

关于javascript - 创建 YouTube AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447867/

相关文章:

iphone - UITableView iPhone App 中的 YouTube 视频

php - 基于YouTube api v3浏览器的上传引发400错误

Javascript:检测窗口何时完全加载

javascript - 即使注册成功,Service Worker 仍显示为已删除

javascript - Controller 内部的 Angular 1.6 绑定(bind)

javascript - 使用 AngularJS 路由器加载 404 状态

javascript - 带 HTML 的 JS 加密

Javascript数组检查值并分配到数组中

javascript - 当运行 block 中存在无限循环时,工厂中的 $http 成功回调不会运行

javascript - YouTube Iframe API 初始化后,player.getPlayerState 不可用