Instant YouTube video search API V3 Version tutorial

In my previous article “instant YouTube video search” tutorial, I just used plain JavaScript with JQuery. In this tutorial I used AngularJS for YouTube instant video search with pagination option and API I used YouTube V3 API.End of the tutorial demo and download option is available for your reference.

Let’s start the tutorial Now.

Step 1: Create the folder structure and files of the project.

Lots of way to organize the file and folder structure in AngularJS project. I used one of the way to organize the folder and Files.

Find the screenshot of the angularJS project folder structure and files

angularJS folder structure and files

Step2: Include all dependent files in index.html

I used bootstrap for styling and for listing the videos. Used angularJS and Angularjs UI router. Include main.js, controller and directives

<!DOCTYPE html>
<html> 
    <head>
        <title>Angularjs instant youtube video search API</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/bootstrap.min.css">
    </head>
    <body ng-app="instantYoutubeSearch" ng-controller="youtubeController">
        <div ui-view></div>
        <script src="lib/angular.min.js"></script>
        <script src="lib/angular-ui-router.min.js"></script>
        <script src="js/main.js"></script>
        <script src="js/controller/controller.js"></script>
        <script src="js/directives/searchBox.js"></script>
        <script src="js/directives/pagination.js"></script>
    </body>
</html>

Step3: Initiate the angular module “instantYoutubeSearch” and route to home page using angular UI router.

“instantYoutubeSearch” is the app name where we have to use it in the template “ng-app=’ instantYoutubeSearch’”. ‘$urlRouterProvider.otherwise("home")’ will route to home page.

Past the below code to “main.js” file.

var app = angular.module('instantYoutubeSearch', ['ui.router']);

app.config(function($stateProvider,$urlRouterProvider){
    $urlRouterProvider.otherwise("home");
    $stateProvider.state("home",{
        url:"/home",
        templateUrl:"templates/home.html"
    });
});

Step4: Create AngularJS controller

Create controller as “youtubeController” and past the below code inside the controller.js

app.controller('youtubeController', function($scope,$http,$filter) {
    $scope.youtubeData = [];
    $scope.nextPage = "";
    $scope.youtubeSearchText = "";
    $scope.getYoutubeData = function(searchText){
        $http.get('https://www.googleapis.com/youtube/v3/search', {
            params: {
                key: "API_KEY",
                type: 'video',
                maxResults: '12',
                pageToken: $scope.nextPage ? $scope.nextPage : '',
                part: 'id,snippet',
                fields: 'items/id,items/snippet/title,items/snippet/description,items/snippet/thumbnails/default,items/snippet/channelTitle,nextPageToken,prevPageToken',
                q: searchText
            }
        }).success( function (data) {
            if (data.items.length === 0) {
                $scope.youtubeData = 'No results were found!';
            }
            $scope.youtubeSearchText = searchText;
            $scope.youtubeData = data.items;
            $scope.nextPageToken = data.nextPageToken;
            $scope.prevPageToken = data.prevPageToken;
        });
    };

    $scope.checkDataLength = function(data){
        return (data.length >=1);
    };

    $scope.callNextPageFn = function(nextPage){
        $scope.nextPage = nextPage;
        $scope.getYoutubeData($scope.youtubeSearchText);
    };
});

Note: replace the API_KEY to your youtube API Key

Step5: Create the custom directive pagination.js and searchBox.js

Pagination directive is used to navigate to next set of searched videos. Open the pagination.js and past the below code inside it.

(function(){
    app.directive("pagination",function(){
        return{
            templateUrl:"templates/pagination.html",
            link:function(scope,elem,attrs){
                console.log(scope);
            }
        }
    });
})();

searchBox.js directive is used for instant search functionality. When user types the search word, it will connect the controller and call the YouTube API v3 version to fetch the videos and display it in the page. Use the below code and past it in searchBox.js

(function(){
    app.directive("searchBox",function(){
        return{
            templateUrl:"templates/searchBox.html",
            link:function(scope,elem,attrs){
                console.log(scope);
            }
        }
    });
})();

Step6: Create the templates for instant search box, video list and navigation (YouTube pagination)

Open the searchBox.html and past the below code in it.

<div class="well"> 
	 <form class="form">
	  	<input type="search" ng-model="youtubeSearchText" ng-change="getYoutubeData(youtubeSearchText)" name="hyv-search" id="hyv-search" placeholder="Search..." class="ui-autocomplete-input form-control input-lg" autocomplete="off">
	</form>
</div>

Open the pagination.html and past the below code in it.

<div style="text-align:center;" ng-if="checkDataLength(youtubeData)">
    <input type="hidden" id="pageToken" value="">
    <div class="btn-group" role="group" aria-label="...">
      <button type="button" ng-show="prevPageToken" id="pageTokenPrev" ng-click="callNextPageFn(prevPageToken)" class="btn btn-default">Prev</button>
      <button type="button" id="pageTokenNext" ng-click="callNextPageFn(nextPageToken)" class="btn btn-default">Next</button>
    </div>
</div>

Open the home.html and past the below code in it.

<search-box></search-box>
<pagination></pagination>
<div ng-if="checkDataLength(youtubeData)">
    <div class="panel-body">
      <div class="col-sm-4 col-lg-4 col-md-4" ng-repeat="data in youtubeData">
        <div class="well well-sm media">
            <a class="thumbnail pull-left" target="_block" href="https://www.youtube.com/watch?v={{data.id.videoId}}">
                <img alt="{{data.snippet.title}}" src="{{data.snippet.thumbnails.default.url}}" width="120" height="90">
            </a>
            <div class="media-body">
                <a target="_block" href="https://www.youtube.com/watch?v={{data.id.videoId}}">{{data.snippet.title}}</a>
                <p>By <a target="_block" href="https://www.youtube.com/channel/{{data.snippet.channelId}}"><span class="label label-info">{{data.snippet.channelTitle}}</span></a></p>
            </div>
        </div>
       </div>
    </div>
</div>

Instant YouTube video search API Demo Screenshot

Angularjs instant youtube video search API demo

Download Demo

Advertisement

Google Matched Content...