如何使用angularjs加载YouTube视频?

时间:2015-02-14 16:34:12

标签: angularjs

我正试图通过javascript代码延迟加载youtube视频,如here所述。

以下是代码:

function optimizeYouTubeEmbeds() {
// Get all iframes
var frames = document.getElementsByTagName('iframe');

// Loop through each iframe in the page.
for (var i = 0; i < frames.length; i++) {

    // Find out youtube embed iframes.
    if (frames[i].src && frames[i].src.length > 0 && frames[i].src.match(/http(s)?:\/\/www\.youtube\.com/)) {

        // For Youtube iframe, extract src and id.
        var src = frames[i].src;
        var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
        var id = (src.match(p) ? RegExp.$1 : false);
        if (id == false) { continue; }

        // Get width and height.
        var w = frames[i].width;
        var h = frames[i].height;
        if (src == '' || w == '' || h == '') { continue; }

        // Thease are to position the play button centrally.
        var pw = Math.ceil(w / 2 - 38.5);
        var ph = Math.ceil(h / 2 + 38.5);

        // The image+button overlay code.
        var code = '<a href="#"  onclick="LoadYoutubeVidOnPreviewClick(\'' + id + '\',' + w + ',' + h + ');return false;" id="skipser-youtubevid-' + id + '"><img src="http://i.ytimg.com/vi/' + id + '/hqdefault.jpg" style="" /></a>';

        // Replace the iframe with a the image+button code.
        var div = document.createElement('div');
        div.innerHTML = code;
        div = div.firstChild;
        frames[i].parentNode.replaceChild(div, frames[i]);
        i--;
    }
}
}

// Replace preview image of a video with it's iframe.
function LoadYoutubeVidOnPreviewClick(id, w, h) {
var code = '<iframe src="https://www.youtube.com/embed/' + id + '/?    autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1" width="' + w + '" height="' + h + '" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>';
var iframe = document.createElement('div');
iframe.innerHTML = code;
iframe = iframe.firstChild;
var div = document.getElementById("skipser-youtubevid-" + id);
div.parentNode.replaceChild(iframe, div);
}

此代码在将项目切换为有条理的处理方式之前有效。 我最初认为我可以将该代码包装在$ scope中并调用它,但这不起作用。以下是我检索视频的代码:

$scope.renderHtml = function (html) {
    return $sce.trustAsHtml(html);
};
$scope.Videos = [];
$scope.getVideos = function() {

    // api call
    $http.get('/api/Videos/AllVideos')
        .success(function(data) {


            $scope.Videos = data;

        });

};
$scope.getVideos();

以下是呈现它的html标记:

<div ng-repeat="vid in Videos">
<div ng-bind-html="renderHtml(vid.url)"></div>
</div>

vid.url包含所有iframe标记信息等。我需要做些什么来完成这项工作?

0 个答案:

没有答案