Mohamed Sheshtawy
Mohamed Sheshtawy

Reputation: 85

How to play youtube video using angularjs

All the following code is work successfully to get youtube playlist and display it with no problem. But I can't play any video from this list using angular js.

Angular JS

   var app = angular.module("myApp", []);
   app.controller("myCtrl", function ($scope, $http) {
       //contentDetails - snippet

       $http.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLlMsyZB0poTDYImmOliKyiC-jpAFUsr6X&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw')
            .then(function (response) {
                $scope.records = response.data.items;
            });

       $scope.PlayFun = function (Val) {
           var Vid_ID = Val;
           var New_Vid = "<iframe width='450' height='283' src='https://www.youtube.com/embed/" + Vid_ID + "?autoplay=1&loop=1&rel=0&wmode=transparent' frameborder='0' allowfullscreen wmode='Opaque'></iframe>";
           var Vid_Elm = document.getElementById("video");

           Vid_Elm.setAttribute("crs", New_Vid);

       };

   });

HTML

    <iframe id="video" style="position:fixed;top:150px;right:50px;" width="420" height="315" src="//www.youtube.com/embed/9B7te184ZpQ?rel=0" frameborder="0" allowfullscreen></iframe>

    <br />

    <ul data-ng-app="myApp" data-ng-controller="myCtrl">
        <li data-ng-repeat="x in records">
                    <img class="img-thumbnail" style="width:100px; height:80px;" 
                    src="{{x.snippet.thumbnails.default.url}}" />
            <br />

            <input data-ng-click="PlayFun(x.snippet.resourceId.videoId)" type="button" value="{{x.snippet.title}}" />
        </li>
    </ul>

My problem specifically is in "$scope.PlayFun" where I can't run a video from the list by video id using angular js. My approach is to change iframe html on ng-click to pass new selected Vid_ID and to make it "autoplay=1" put it doesn't work.

Upvotes: 1

Views: 4324

Answers (1)

Tim Andrews
Tim Andrews

Reputation: 847

You can set the src of the iframe to ng-src like so:

<iframe id="video" style="position:fixed;top:150px;right:50px;" width="420" height="315" ng-src="{{videoSource}}" frameborder="0" allowfullscreen></iframe>

And in your controller you simply change the url of video source and it will automatically change the video source. You do need to trust as resource url though for security (which means injected $sce as well)

$scope.videoSource = $sce.trustAsResourceUrl("//www.youtube.com/embed/9B7te184ZpQ?rel=0");

Working PLunker demo

Upvotes: 2

Related Questions