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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
<!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> |
Now make angular-youtube-embed.js
file inside the same directory and copy paste the below code
angular-youtube-embed.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
/* 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(); }); } }; }]); |
Now make a the.js
file inside the same directory and copy paste the below code
the.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
// 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; } } }; }); |
Now if you open the index.html
file inside the browser you will see the following output
Official Github Repository