我有类似的 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 可以具有以下任何形式:
- http://www.youtube.com/watch?v=iwGFalTRHDA
- http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
- http://youtu.be/iwGFalTRHDA
- http://youtu.be/n17B_uFF4cA
- http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
- http://www.youtube.com/watch?v=t-ZRX8984sc
- http://youtu.be/t-ZRX8984sc
其次,您需要使用有效的 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/