w3tweaks.com
  • Effects
    • Scroll Effects
    • Text Effects
    • Shadow
  • Essentials
    • Arrows
    • Buttons
    • Background Patterns
    • Border Examples
    • Cards
    • Color Palettes
    • Dividers
    • Link styles
    • Loaders
    • Modal Windows
    • Notifications
    • Progress bar
    • Quote styles
    • Spinner
    • Tooltips
  • Media
    • Calendars
    • Carousels
    • Clocks
    • Gallery
    • Music Players
    • Sliders
    • Slideshows
    • Tables
    • Thumbnails
  • Navigation
  • Inputs
    • Range Sliders
    • Checkboxes
    • Toggle Switches
  • Scripts
    • Angularjs
    • Backbone.js
    • bootstrap
    • jQuery
    • ReactJs
    • JavaScript
    • Syntax Highlighters
    • tryit editor
    • PHP
  • API’s
    • Facebook
    • Google
    • Indeed
    • Twitter
    • YouTube
  • Tools
w3tweaks.com
  • Effects
    • Scroll Effects
    • Text Effects
    • Shadow
  • Essentials
    • Arrows
    • Buttons
    • Background Patterns
    • Border Examples
    • Cards
    • Color Palettes
    • Dividers
    • Link styles
    • Loaders
    • Modal Windows
    • Notifications
    • Progress bar
    • Quote styles
    • Spinner
    • Tooltips
  • Media
    • Calendars
    • Carousels
    • Clocks
    • Gallery
    • Music Players
    • Sliders
    • Slideshows
    • Tables
    • Thumbnails
  • Navigation
  • Inputs
    • Range Sliders
    • Checkboxes
    • Toggle Switches
  • Scripts
    • Angularjs
    • Backbone.js
    • bootstrap
    • jQuery
    • ReactJs
    • JavaScript
    • Syntax Highlighters
    • tryit editor
    • PHP
  • API’s
    • Facebook
    • Google
    • Indeed
    • Twitter
    • YouTube
  • Tools
w3tweaks.com
Home Script Angularjs

YouTube V3 API to get single Video Information using Angular JS

W3TWEAKS by W3TWEAKS
November 26, 2019
in Angularjs

In my recent comment box one of my reader asking me to create a demo for the YouTube single video snippet using AngularJS ui-router. I have already created the tutorial and demo for YouTube single video snippet using core JS and with using jQuery (link). I have created the tutorial again using AngularJS for my reader who requested the demo and for my users too. This tutorial will explain you how to load single YouTube video and it’s information in the webpage using AngularJS.

Before going to the tutorial, we have to create folders and files in the structured way for the Angular js project. Please create the folders and the files like below. This is one of the ways we can create folder and files. As we all know AngularJS support MVVC and MVC. Before starting the project keep in mind, have to align the files to the respective folders. In our tutorial I’m using MVC. Please find the folder structure below.

You might also like

Iterate javascript object keys using angularjs ngRepeat

Iterate javascript object keys using angularjs ngRepeat

October 27, 2020
Enable and Disable drop down box using angularjs ngDisabled

Enable and Disable drop down box using angularjs ngDisabled

November 26, 2019

YouTube V3 API to get single Video Information using Angular JS 1

This demo will show video Hits, title of the video, description, video duration and display video

JavaScript: Controller

Open mainController.js

Once the folders and files are created, open the js/controller/mainController.js controller and place the below code.

var app = angular.module('youtube', ['ui.router']);
app.config(function($stateProvider, $sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist(['self', '*://www.youtube.com/**']);
    $stateProvider.state('home', {
        url: '/',
        templateUrl: 'templates/mainPage.html'
    }).state('video', {
        url: '/video/:videoId/',
        params: {
            videoId: null
        },
        templateUrl: 'templates/video.html'
    });
});
app.controller('mainController', ['$scope', 'youtubeService', '$state', function($scope, youtubeService, $state) {
    $scope.title = "Youtube";
    $state.go("home");
    var response = youtubeService.getVideoList().then(function(data) {
        $scope.data = data.data.items;
    });
}]);

In the above code you will notice the “$sceDelegateProvider.resourceUrlWhitelist”. This will make sure if any cross domain URL / link is called the above code will take care of bypassing the error or warning. Here we can mention all the allowed url with mode as “safe”. In case if we want to block any URL in AngularJS project use the “resourceUrlBlacklist” instead of “resourceUrlWhitelist”. If you want to get more idea about allowing or blocking the URL from AngularJS project please look at this link.

Open videoController.js

Open the controller and place the below code.

(function() {
    app.controller('videoController', function($stateParams, $scope, $state, youtubeService) {
        console.log($stateParams);
        var url = "https://www.youtube.com/embed/" + $stateParams.videoId;
        $scope.videoUrl = url;
        $scope.onBack = function() {
            $state.go('home');
        };

        function numberformat(number, n, x) {
            var re = '(\\d)(?=(\\d{' + (x || 3) + '})+' + (n & gt; 0 ? '\\.' : '</pre> <
                pre > & nbsp; < /pre> <
                pre class = "prettyprint linenums" > apos;) + ')';
            return number.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$1,');
        };
        $scope.getVideoDetails = function() {
            youtubeService.getVideoDetails($stateParams.videoId).then(function(data) {
                $scope.data = data.data.items;
                $scope.viewCount = numberformat(parseInt($scope.data[0].statistics.viewCount)) console.log($scope.data);
            });
        };
        $scope.getVideoDetails();
    });
})();

JavaScript: Directive

Open videoInfo.js

Open videoInfo.js directive from js/directive/ and place the below code

(function() {
    app.directive('videoInfo', function($state) {
        return {
            templateUrl: 'templates/videoDesc.html',
            scope: {
                title: '@',
                url: '@',
                id: "@"
            },
            link: function(scope, elem, attr) {
                scope.openVideo = function(item) {
                    $state.go('video', {
                        videoId: scope.id
                    });
                }
            }
        }
    });
})();

JavaScript: Services

Open youtubeService.js

Open youtubeService.js directive from js/services/ and place the below code

(function() {
    app.service('youtubeService', function($http, $q) {
        var response, key = "API_KEY",
            baseUrl = "https://www.googleapis.com/youtube/v3/videos";

        function getVideoList() {
            var defer = $q.defer();
            $http({
                method: 'GET',
                url: baseUrl + '?part=snippet&amp;chart=mostPopular&amp;maxResults=10&amp;key=' + key
            }).then(function successCallback(response) {
                defer.resolve(response);
            }, function errorCallback(response) {});
            return defer.promise;
        };

        function getVideoDetails(id) {
            var defer = $q.defer();
            $http({
                method: 'GET',
                url: baseUrl + '?part=snippet,contentDetails,statistics,status&amp;fields=items(id,snippet,statistics,contentDetails,status)&amp;key=' + key + '&amp;id=' + id
            }).then(function successCallback(response) {
                defer.resolve(response);
            }, function errorCallback(response) {});
            return defer.promise;
        };
        return {
            getVideoList: getVideoList,
            getVideoDetails: getVideoDetails,
            getResponse: response
        }
    });
})();

Note: Replace “API_KEY” to your YouTube API KEY

HTML: index.html

Open index.html

Open index.html and place below code

<html>

<head>
    <link rel="stylesheet" href="css/maincss.css" type="text/css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
    <script src="//code.jquery.com/jquery-2.1.4.js" type="text/javascript"></script>
    <script src="js/controller/mainController.js"></script>
    <script src="js/controller/videoController.js"></script>
    <script src="js/directive/videoInfo.js"></script>
    <script src="js/services/youtubeService.js"></script>
</head>

<body ng-app="youtube" ng-controller="mainController">
    <div ui-view></div>
</body>

</html>

Open mainPage.html

Open mainPage.html from templates folder and place below code

<div ng-repeat="item in data">
    <video-info title="{{item.snippet.title}}" id="{{item.id}}" url="{{item.snippet.thumbnails.default.url}}"> </video-info>
</div>

Open video.html

Open video.html from templates folder and place below code

<div class="row-fluid" ng-controller="videoController">
    <main id="content" role="main" class="span12">
        <button ng-click="onBack()">Back</button>
        <!-- Begin Content -->
        <div id="hyv-page-container" style="clear:both;" ng-repeat="items in data">
            <div class="hyv-content-alignment">
                <!-- Player content start -->
                <div id="hyv-player-page" class="hyv-player-watch">
                    <div class="hyv-content-left hyv-player">
                        <div id="hyv-player-api" class="hyv-player-width hyv-player-height hyv-off-screen-target hyv-player-api">
                            <iframe width="100%" height="100%" ng-src={{videoUrl}} frameborder="0" allowfullscreen></iframe>
                        </div>
                        <div id="hyv-watch-content" class="hyv-watch-main-col">
                            <!-- Video header start -->
                            <div id="hyv-watch-header" class="hyv-card hyv-card-has-padding">
                                <!-- Video title start -->
                                <div id="hyv-watch-headline" class="clearfix">
                                    <div id="hyv-watch-headline-title">
                                        <h1 class="hyv hyv-watch-title-container"> 	                                			<span id="hyv-eow-title" class="hyv-watch-title" dir="ltr" title="">                                                     {{items.snippet.title}}                                                 </span> 	                            			</h1> </div>
                                </div>
                                <!-- Video title end -->
                                <!-- Video user header -->
                                <div id="hyv-watch-user-header">
                                    <a class="hyv-user-photo"> <span class="hyv-video-thumb hyv-thumb hyv-thumb-48"> 					                            <span class="hyv-thumb-square"> 					                               <span class="hyv-thumb-clip">                                                     <img width="48" height="48" src="{{items.snippet.thumbnails.default.url}}" />                                                     </span> </span>
                                        </span>
                                    </a>
                                    <div class="hyv-user-info">{{items.snippet.channelTitle}}</div>
                                    <div class="hyv-social-send"></div>
                                </div>
                                <!-- Video user header end -->
                                <!-- Social buttons start-->
                                <div id="hyv-watch-social-buttons" class="hyv-watch-social-buttons clearfix">
                                    <div id="hyv-watch-social-actions" class="hyv-watch-social-actions hyv-button-group"></div>
                                    <div id="hyv-watch-social-actions-like" class="hyv-watch-social-actions-like">
                                        <div id="hyv-watch-views-info">
                                            <div class="hyv-watch-view-count">{{viewCount}}</div>
                                        </div>
                                    </div>
                                </div>
                                <!-- Social buttons end-->
                            </div>
                            <!-- Video header end -->
                            <!-- Video details start -->
                            <div id="hyv-watch-details" class="hyv-card hyv-card-has-padding">
                                <div id="hyv-watch-description">
                                    <div id="hyv-watch-description-content">
                                        <div id="hyv-watch-description-clip">
                                            <div id="hyv-watch-uploader-info"> <strong class="hyv-watch-time-text">Published on  {{items.snippet.publishedAt}}</strong> </div>
                                            <div id="hyv-watch-description-text" class="">
                                                <p id="hyv-eow-description">{{items.snippet.description}}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Video details end -->
                        </div>
                    </div>
                    <div id="hyv-watch-sidebar" class="hyv-watch-sidebar">
                        <div id="hyv-watch-sidebar-contents" class="hyv-card hyv-card-has-padding">
                            <!-- Ads width 300px holder start -->
                            <div id="hyv-watch-sidebar-ads">
                                <div id="hyv-watch-channel-brand-div" class="">
                                    <div id="hyv-watch-channel-brand-div-text">Advertisement</div>
                                    <div id="hyv-companion-ad-div"></div>
                                </div>
                            </div>
                            <!-- Ads width 300px holder end -->
                        </div>
                    </div>
                </div>
                <!-- Player content end -->
            </div>
        </div>
    </main>
</div>

Open videoDesc.html

Open videoDesc.html from templates folder and place below code

<div> <img src="{{url}}" ng-click="openVideo(item)" />
    <div>{{title}}</div>
</div>

Download Demo

Tags: angular jsAngularjsAngularJS TutorialsAPIinformationtutorialV3videoVideo APIYouTube
Previous Post

Embed YouTube Videos without affecting the website performance

Next Post

Google ads in Angular js app

W3TWEAKS

W3TWEAKS

Since I've had a strong background in front-end development, I took the initiative to start my own website (w3tweaks.com) to share my knowledge with the world.

Related Stories

Iterate javascript object keys using angularjs ngRepeat

Iterate javascript object keys using angularjs ngRepeat

by W3TWEAKS
October 27, 2020

This tutorial will explain how to get or iterate the JavaScript Object keys / Properties using AngularJs ngRepeat. It is...

Enable and Disable drop down box using angularjs ngDisabled

Enable and Disable drop down box using angularjs ngDisabled

by W3TWEAKS
November 26, 2019

In AngularJs we can able to disable or enable the dropdown like jQuery does. Using ngDisabled function in angularjs we...

Select all and Deselect all checkboxes in angularjs

Select all and Deselect all checkboxes in angularjs

by W3TWEAKS
October 22, 2021

This tutorial will explain how to achieve check all and uncheck all checkbox using angularjs and listing all checked values...

Angularjs and JSON list infinite scroll

Angularjs and JSON list infinite scroll

by Vetrivel Pandian
September 19, 2019

JSON is more better way to transmitting the data in server to client. When you have develop large data application,...

Next Post
Google ads in Angular js app

Google ads in Angular js app

Discussion about this post

Popular Posts

100 Creative CSS Cards

41 Multi step HTML forms

13 Free HTML & CSS Dashboard Template Designs

20 HTML & CSS pricing tables

49 CSS Tables

14 Best CSS Dark Mode

11 CSS Shopping Cart UI/UX

42 Cool CSS Avatars For Better UI

89 Best CSS Toggle Switches

55 Useful handpicked CSS Buttons with examples and demos

w3tweaks

We bring you the best frontend collections that will fix perfect for news, magazine, personal blog, etc. Check our landing page for details.

  • Effects
    • Scroll Effects
    • Text Effects
    • Shadow
  • Essentials
    • Arrows
    • Buttons
    • Background Patterns
    • Border Examples
    • Cards
    • Color Palettes
    • Dividers
    • Link styles
    • Loaders
    • Modal Windows
    • Notifications
    • Progress bar
    • Quote styles
    • Spinner
    • Tooltips
  • Media
    • Calendars
    • Carousels
    • Clocks
    • Gallery
    • Music Players
    • Sliders
    • Slideshows
    • Tables
    • Thumbnails
  • Navigation
  • Inputs
    • Range Sliders
    • Checkboxes
    • Toggle Switches
  • Scripts
    • Angularjs
    • Backbone.js
    • bootstrap
    • jQuery
    • ReactJs
    • JavaScript
    • Syntax Highlighters
    • tryit editor
    • PHP
  • API’s
    • Facebook
    • Google
    • Indeed
    • Twitter
    • YouTube
  • Tools