javascript - 如何从 JSON 文件嵌入 youtube 链接

标签 javascript angularjs ionic-framework youtube-javascript-api

我有类似的 JSON 文件

[{"id":"38", "youtube":"https://www.youtube.com/watch?v=PEnuHN-Mqvg"}]

我曾经尝试过 php JavaScript 之类的

var str = data[i].youtube;
var res = str.split("?v="); 
//raplace & is  ?
var str2 = res[1];
var res2 = str2.replace("&", "?");
//asign iframe to url variable
var url = "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/"+res2+"\"  frameborder=\"0\" allowfullscreen></iframe>";
$("#youtube").append(url); //show tag iframe

那么如何在 AngularJS 中应用呢?

最佳答案

首先,我建议使用正则表达式从 YouTube 网址获取视频 ID。 str.split("?v=");并非在所有情况下都有效,因为有效的 youtube 视频 URL 可以具有以下任何形式:

其次,您需要使用有效的 src 为 iframe(要嵌入的代码)构建 html 标记,并将生成的字符串绑定(bind)与 View 。像 {{<iframe src="..">}} 这样的简单插值不管用。所以使用 ng-bind-html

<div ng-bind-html="<iframe src='...'>"></div>

最后你需要$sce使 AngularJS 绑定(bind)产生一个值的服务,该值被标记为可以安全地用于该上下文

<div ng-bind-html="getTrustedHTML('<iframe src=...>')"></div>

在哪里getTrustedHTML()是一个为 Angular 上下文返回可信 HTML 的函数。

  $scope.getTrustedHTML=function(str){
       return $sce.trustAsHtml(str);
  }  

Controller 应该是这样的:

app.controller('MainCtrl', function($scope,$sce, yourService) {
  $scope.name = 'World';

  $scope.data = {};

  //If you want to get the video links from a JSON  
  yourService.getData().then(function(res){
      $scope.data = res.data;
  })  

  $scope.postContent = ''
  /* or directly use $scope.postContent = <youtube URL>
   */

  $scope.parseVideoURL = function(text) {
      var re = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
      return text.replace(re,
          '<iframe height="100%" width="100%" src="http://www.youtube.com/embed/$1" allowfullscreen></iframe>');
  }        

  $scope.publishVideo = function(vid){
    return $scope.parseVideoURL(vid)

  }


  $scope.getTrustedHTML=function(str){
       return $sce.trustAsHtml(str);
  }  
});

这是标记

Enter a  Youtube URL. Eg: 'https://www.youtube.com/watch?v=PEnuHN-Mqvg'
<br><br><br>
<input type='text' ng-model="postContent" >
<div ng-bind-html="getTrustedHTML(publishVideo(postContent))"></div>

<h3>VIDEOS FROM JSON</h3>
<div ng-repeat="v in data" ng-bind-html="getTrustedHTML(publishVideo(v.youtube))"></div>

工作 Plunkr

关于javascript - 如何从 JSON 文件嵌入 youtube 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31376134/

相关文章:

javascript - 如何在 Ionic 3 中包含 .jar 或在 Apex2 中打印

javascript - 如何将匿名 firebase 凭证保存到本地存储以外的其他地方?

javascript - 在加载多个 div 时应用动画

javascript - 如何在将变量作为内容传递时使用 jQuery 将 HTML 元素添加到 div 中?

带参数的 AngularJs 路由

javascript - templateURL 的 AngularJS 问题

javascript - 如何按顺序正确调用异步函数列表?

javascript - 从 javascript 触发按钮点击

javascript - 在 Karma/Jasmine 单元测试中注入(inject) Angular 的 $timeout 服务的实际实现

javascript - 更改帖子的 url 并进入 ngresource