AngularJS Youtube Video Embed IFrame API Video Player in Browser Using angular-youtube-embed Directive in Javascript Full Project For Beginners

AngularJS Youtube Video Embed IFrame API Video Player in Browser Using angular-youtube-embed Directive in Javascript Full Project For Beginners

 

Welcome folks today in this blog post we will be embeding youtube videos as iframe video player in browser using angular-youtube-embed directive in angularjs using javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

index.html

 

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Angular YouTube</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">

    <link rel="stylesheet" href="//brick.a.ssl.fastly.net/Oswald:400">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

    <style>
      * {
        box-sizing: border-box;
      }

      body {
        color: #444;
        font-family: "Arial", sans-serif;
      }

      header {
        width: 100%;
        background-color: #77BCF6;
        color: #FFF;
        padding: 2.0rem 1.0rem;
        text-align: center;
        border-bottom: 3px solid #FFACAC;
      }

      h1, h2, h3, h4, h5 {
        font-family: "Oswald", sans-serif;
      }

      h1 {
        font-size: 2.8rem;
        line-height: 1.2;
        margin: 0.8rem 0;
        text-shadow: 1px 1px 1px #4181B8;
      }

      h3 {
        font-size: 2.0rem;
        line-height: 1.3;
        margin: 0.6rem;
      }

      p {
        font-size: 1.1rem;
        line-height: 1.3;
      }

      code {
        font-family: Courier, monospace;;
        margin: 1.0rem 0;
      }

      .container {
        max-width: 700px;
        margin: 0 auto;
      }

      .video-wrapper {
        margin: 4.0rem 0;
      }

      .video-detail {
        margin: 1.0rem 2.0rem;
        border-left: 6px solid #FFACAC;
        padding: 0.6rem;
      }

      .controls {
        margin: 1.0rem 2.0rem;
      }

      .controls .border-button {
        font-size: 1.6rem;
        line-height: 1.6;
      }

      .play,
      .pause {
        width: 49%;
      }

      .toggle {
        width: 100%;
      }

      .pause {
        float: right;
      }

      footer {
        text-align: center;
        padding-bottom: 6.0rem;
      }

      .border-button {
        color: #77BCF6;
        background-color: #FFF;
        font-family: "Oswald", sans-serif;
        border: 2px solid #77BCF6;
        border-radius: 4px;
        outline: none;
        text-decoration: none;
        cursor: pointer;

        transition: box-shadow 300ms;
      }

      .border-button:hover {
        box-shadow: 0px 2px 4px rgba(119, 188, 246, 0.5);
      }

      .border-button:active {
        transform: translateY(2px);
      }

      .view-github {
        display: block;
        margin: 0 1.0rem;
        font-size: 1.8rem;
        line-height: 1.2;
        padding: 1.0rem 0.8rem;
      }

      .view-advanced {
        display: inline-block;
        text-decoration: none;
        color: #444;
        font-size: 1.2rem;
        line-height: 1.4;
        margin-top: 1.0rem;
      }

      .view-advanced:hover {
        border-bottom: 2px solid #77BCF6;
      }

      /* .embed-* is from bootstrap, for responsive videos */
      .embed-responsive {
        position: relative;
        display: block;
        height: 0;
        padding: 0;
        overflow: hidden;
        background-color: rgba(240, 240, 240, 0.4);
      }

      .embed-responsive.embed-responsive-16by9 {
        padding-bottom: 56.25%;
      }

      .embed-responsive-item {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border: 0;
      }

      /* hljs is higlight.js, for code blocks */
      .hljs {
        display: block;
        overflow-x: auto;
        padding: 1.0rem;
        background: rgba(240, 240, 240, 0.4);
        -webkit-text-size-adjust: none;
        font-size: 1.1rem;
        border-radius: 4px;
      }

      .hljs-keyword,.hljs-id,.hljs-title,.hljs-built_in,.css .hljs-tag,.hljs-javadoctag,.hljs-phpdoc,.hljs-dartdoc,.hljs-yardoctag,.smalltalk .hljs-class,.hljs-winutils,.bash .hljs-variable,.apache .hljs-tag,.hljs-type,.hljs-typename,.tex .hljs-command,.asciidoc .hljs-strong,.markdown .hljs-strong,.hljs-request,.hljs-status {
        font-weight: 700;
      }

      .hljs-title,
      .hljs-keyword {
        color: #659FD0;
      }

      .hljs-comment {
        color: #99B1BB;
      }

      .hljs-value,
      .hljs-string {
        color: #E87E7E;
      }

      .hljs span {
        line-height: 1.2;
      }

      ::selection {
        background: #FFACAC;
      }
      ::-moz-selection {
        background: #FFACAC;
      }
    </style>
  </head>
  <body>
    <header>
      <div class="container">
        <h1>Angular YouTube Embed</h1>
        <p>Embed a YouTube player with a simple directive</p>
      </div>
    </header>

    <div ng-view></div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-route.min.js"></script>
    <script src="https://www.youtube.com/iframe_api"></script>
    <script src="angular-youtube-embed.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
    <script src="http://pc035860.github.io/angular-highlightjs/angular-highlightjs.min.js"></script>
    <script src="the.js"></script>
  </body>
</html>

 

See also  Angular 9 Tutorial to Convert HTML to PDF Using jsPDF & html2canvas Library Full Project For Beginners

 

Now make angular-youtube-embed.js file inside the same directory and copy paste the below code

 

angular-youtube-embed.js

 

/* global YT */
angular.module('youtube-embed', [])
.service ('youtubeEmbedUtils', ['$window', '$rootScope', function ($window, $rootScope) {
    var Service = {}

    // adapted from http://stackoverflow.com/a/5831191/1614967
    var youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
    var timeRegexp = /t=(\d+)[ms]?(\d+)?s?/;

    function contains(str, substr) {
        return (str.indexOf(substr) > -1);
    }

    Service.getIdFromURL = function getIdFromURL(url) {
        var id = url.replace(youtubeRegexp, '$1');

        if (contains(id, ';')) {
            var pieces = id.split(';');

            if (contains(pieces[1], '%')) {
                // links like this:
                // "http://www.youtube.com/attribution_link?a=pxa6goHqzaA&u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare"
                // have the real query string URI encoded behind a ';'.
                // at this point, `id is 'pxa6goHqzaA;u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare'
                var uriComponent = decodeURIComponent(pieces[1]);
                id = ('http://youtube.com' + uriComponent)
                        .replace(youtubeRegexp, '$1');
            } else {
                // https://www.youtube.com/watch?v=VbNF9X1waSc&feature=youtu.be
                // `id` looks like 'VbNF9X1waSc;feature=youtu.be' currently.
                // strip the ';feature=youtu.be'
                id = pieces[0];
            }
        } else if (contains(id, '#')) {
            // id might look like '93LvTKF_jW0#t=1'
            // and we want '93LvTKF_jW0'
            id = id.split('#')[0];
        }

        return id;
    };

    Service.getTimeFromURL = function getTimeFromURL(url) {
        url = url || '';

        // t=4m20s
        // returns ['t=4m20s', '4', '20']
        // t=46s
        // returns ['t=46s', '46']
        // t=46
        // returns ['t=46', '46']
        var times = url.match(timeRegexp);

        if (!times) {
            // zero seconds
            return 0;
        }

        // assume the first
        var full = times[0],
            minutes = times[1],
            seconds = times[2];

        // t=4m20s
        if (typeof seconds !== 'undefined') {
            seconds = parseInt(seconds, 10);
            minutes = parseInt(minutes, 10);

        // t=4m
        } else if (contains(full, 'm')) {
            minutes = parseInt(minutes, 10);
            seconds = 0;

        // t=4s
        // t=4
        } else {
            seconds = parseInt(minutes, 10);
            minutes = 0;
        }

        // in seconds
        return seconds + (minutes * 60);
    };

    Service.ready = false;

    function applyServiceIsReady() {
        $rootScope.$apply(function () {
            Service.ready = true;
        });
    };

    // If the library isn't here at all,
    if (typeof YT === "undefined") {
        // ...grab on to global callback, in case it's eventually loaded
        $window.onYouTubeIframeAPIReady = applyServiceIsReady;
        console.log('Unable to find YouTube iframe library on this page.')
    } else if (YT.loaded) {
        Service.ready = true;
    } else {
        YT.ready(applyServiceIsReady);
    }

    return Service;
}])
.directive('youtubeVideo', ['$window', 'youtubeEmbedUtils', function ($window, youtubeEmbedUtils) {
    var uniqId = 1;

    // from YT.PlayerState
    var stateNames = {
        '-1': 'unstarted',
        0: 'ended',
        1: 'playing',
        2: 'paused',
        3: 'buffering',
        5: 'queued'
    };

    var eventPrefix = 'youtube.player.';

    $window.YTConfig = {
        host: 'https://www.youtube.com'
    };

    return {
        restrict: 'EA',
        scope: {
            videoId: '=?',
            videoUrl: '=?',
            player: '=?',
            playerVars: '=?',
            playerHeight: '=?',
            playerWidth: '=?'
        },
        link: function (scope, element, attrs) {
            // allows us to $watch `ready`
            scope.utils = youtubeEmbedUtils;

            // player-id attr > id attr > directive-generated ID
            var playerId = attrs.playerId || element[0].id || 'unique-youtube-embed-id-' + uniqId++;
            element[0].id = playerId;

            // Attach to element
            scope.playerHeight = scope.playerHeight || 390;
            scope.playerWidth = scope.playerWidth || 640;
            scope.playerVars = scope.playerVars || {};

            // YT calls callbacks outside of digest cycle
            function applyBroadcast () {
                var args = Array.prototype.slice.call(arguments);
                scope.$apply(function () {
                    scope.$emit.apply(scope, args);
                });
            }

            function onPlayerStateChange (event) {
                var state = stateNames[event.data];
                if (typeof state !== 'undefined') {
                    applyBroadcast(eventPrefix + state, scope.player, event);
                }
                scope.$apply(function () {
                    scope.player.currentState = state;
                });
            }

            function onPlayerReady (event) {
                applyBroadcast(eventPrefix + 'ready', scope.player, event);
            }

            function onPlayerError (event) {
                applyBroadcast(eventPrefix + 'error', scope.player, event);
            }

            function createPlayer () {
                var playerVars = angular.copy(scope.playerVars);
                playerVars.start = playerVars.start || scope.urlStartTime;
                var player = new YT.Player(playerId, {
                    height: scope.playerHeight,
                    width: scope.playerWidth,
                    videoId: scope.videoId,
                    playerVars: playerVars,
                    events: {
                        onReady: onPlayerReady,
                        onStateChange: onPlayerStateChange,
                        onError: onPlayerError
                    }
                });

                player.id = playerId;
                return player;
            }

            function loadPlayer () {
                if (scope.videoId || scope.playerVars.list) {
                    if (scope.player && typeof scope.player.destroy === 'function') {
                        scope.player.destroy();
                    }

                    scope.player = createPlayer();
                }
            };

            var stopWatchingReady = scope.$watch(
                function () {
                    return scope.utils.ready
                        // Wait until one of them is defined...
                        && (typeof scope.videoUrl !== 'undefined'
                        ||  typeof scope.videoId !== 'undefined'
                        ||  typeof scope.playerVars.list !== 'undefined');
                },
                function (ready) {
                    if (ready) {
                        stopWatchingReady();

                        // URL takes first priority
                        if (typeof scope.videoUrl !== 'undefined') {
                            scope.$watch('videoUrl', function (url) {
                                scope.videoId = scope.utils.getIdFromURL(url);
                                scope.urlStartTime = scope.utils.getTimeFromURL(url);

                                loadPlayer();
                            });

                        // then, a video ID
                        } else if (typeof scope.videoId !== 'undefined') {
                            scope.$watch('videoId', function () {
                                scope.urlStartTime = null;
                                loadPlayer();
                            });

                        // finally, a list
                        } else {
                            scope.$watch('playerVars.list', function () {
                                scope.urlStartTime = null;
                                loadPlayer();
                            });
                        }
                    }
            });

            scope.$watchCollection(['playerHeight', 'playerWidth'], function() {
                if (scope.player) {
                    scope.player.setSize(scope.playerWidth, scope.playerHeight);
                }
            });

            scope.$on('$destroy', function () {
                scope.player && scope.player.destroy();
            });
        }
    };
}]);

 

See also  Angular 9 jsPDF Billing Invoice PDF Generator Using Bootstrap 4 Web App Using Javascript Full Project For Beginners

 

Now make a the.js file inside the same directory and copy paste the below code

 

the.js

 

// Create your app with 'youtube-embed' dependency
var myApp = angular.module('myApp', ['youtube-embed', 'ngRoute', 'hljs']);

myApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider
   .when('/', {
    templateUrl: 'demo/the.html',
    controller: 'TheCtrl'
  })
  .when('/advanced', {
    templateUrl: 'demo/advanced.html',
    controller: 'AdvancedCtrl'
  })
  .otherwise('/');
}]).run(function ($rootScope, $window) {
  $rootScope.$on('$routeChangeSuccess', function () {
    $window.scrollTo(0, 0);
  });
});

// Inside your controller...
myApp.controller('TheCtrl', function ($scope) {
    // have a video ID
    $scope.theBestVideo = 'sMKoNBRZM1M';

    // or a URL
    $scope.anotherGoodOne = 'https://www.youtube.com/watch?v=18-xvIjH8T4';
});

myApp.controller('AdvancedCtrl', function ($scope) {

    $scope.specifiedTime = {
        url: 'https://www.youtube.com/watch?v=Im4TO03CuF8#t=10s',
        player: null
    };

    $scope.looper = {
        video: 'u2-ZGCoKh-I',
        player: null
    };

    $scope.$on('youtube.player.ended', function ($event, player) {
        if (player === $scope.looper.player) {
            player.playVideo();
        }
    });

    $scope.custom = {
        video: 'FGXDKrUoVrw',
        player: null,
        vars: {
            controls: 0
        }
    };

    $scope.conditional = {
        video: '-m-vVKHideI',
        visible: false,
        toggle: function () {
            this.visible = !this.visible;
        },
        vars: {
            autoplay: 1
        }
    };

    $scope.playlist = {
        vars: {
            list: 'PLISo53ifQd_iBPpybJay-SCAULHsoRicc'
        }
    };

    var first = 'biZLZZFb468';
    var second = 'lbVdyPZiOLM';
    $scope.dynamic = {
        video: first,
        change: function () {
            if ($scope.dynamic.video === first) {
                $scope.dynamic.video = second;
            } else {
                $scope.dynamic.video = first;
            }
        }
    };
});

 

See also  Angular 9 jsPDF GST Billing Invoice Generator to Build PDF Documents Using jspdf-Autotable Library Deployed to Heroku in Browser Full Project For Beginners

 

Now if you open the index.html file inside the browser you will see the following output

 

 

 

 

Official Github Repository

 

Leave a Reply