Thursday 27 October 2016

Create a Hybrid Mobile App with Ionic Framework and AngularJS

Below is a step by step guide to recreating this app from scratch. Let’s start!
Step 1: Make sure you have installed Node.js
Open Terminal from you Mac or PC, type in
$ node -v
If you do not see a version number, please install node.js
Step 2: install the latest Cordova and Ionic command-line tools.
$ npm install -g cordova ionic
Step 3: Follow the Android and iOs platform guides to install required platform dependencies.
If you have any questions regarding the above 3 steps, please reference to Ionic Official Getting Started.
Check all the installation by typing $ ionic info in your command line tool to check the version number of all the required pieces.
Step 4: Create a new blank project with Ionic CLI tool
Go into the folder you want your project to be, for example: $ cd mytestproject/. Then, use ionic start command to create a new project using blank template:
$ ionic start youtubevideo blank
cd into this new folder $ cd youtubevideo/ and type $ ionic serve to start up your project.
Step 5: Edit app.js
Open the project you just created in your text editor. Look into www/ folder and under js/ folder you can find the app.js file – the file control all the logic of the app, that Ionic created for us already.
Let’s make the Angular Module more expressive by introducing a new variable called App like so:
(function() {
  var app = angular.module('youtubevideo', ['ionic']);
  app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      if(window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if(window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  });
}());
As you see the code, I also change the name of the app from starter to youtubevideo.
Don’t forget to open up index.html and change the <body ng-app="starter"> into <body ng-app="youtubevideo">.
Step 6: Create a controller – the business logic – for the app to get the YouTube Data we want.
 app.controller('mycontroller', function($scope, $http){
   $scope.videos = [];
 });
We need Angular $scope and $http service to connect with YouTube using YouTube API V3. We also create an empty videos array to store the videos we get from YouTube. For now, we will just copy and paste some dummy data to populate the videos model.
$scope.videos = [
{
  title: "My first video",
  date: "1-1-2015",
  thumbnails: "http://i.ytimg.com/vi/bJp1ptX4F3M/maxresdefault.jpg",
}, 
{
  title: "My second video",
  date: "5-7-2015",
  thumbnails: "http://i.ytimg.com/vi/NA2VerbOyt0/maxresdefault.jpg",
}
]
Now connect the controller to our index.html page:
Change <body ng-app="youtubevideo"> to <body ng-app="youtubevideo" 
ng-controller="mycontroller">.
While we at it, let’s update the HTML template to display the dummy data.
<div class="list card" ng-repeat="video in videos">
      <div class="item item-text-wrap">
        <h2>{{video.title}}</h2>
        <p><i class="ion ion-ios-calendar-outline"></i> {{video.date | limitTo: 10}}</p>
      </div>
      <div class="item item-image">
          <img ng-src="{{video.thumbnails}}">
      </div>

    </div>
So in here, we use the Ionic card directive. More info how to use it here:http://ionicframework.com/docs/components/#card-showcase To populate the dummy data, we use the standard angularJS loop directive – ng-repeat. It just act like a for loop and loop tho all the object in the videos array and display it on the HTML. For more info about ng-repeat, take a look at Angular official docs here:https://docs.angularjs.org/api/ng/directive/ngRepeat
We also use the awesome Ionicons. And the ionic outline button for the share button.
Please save the project and review what you have done with $ ionic serve. Right now, it is also a good time to review your app on iOs or Android simulators. In your terminal, type
$ ionic platform add ios
$ ionic platform add android
If you have not installed iOs simulator, now it is a good time to add it as well if you are on a mac.
$ npm -g install ios-sim
If you have Xcode installed in your mac, running follow command will deploy your app onto iOs simulator:
$ ionic emulate ios -lc
You can also see the code and console logging via Safari developer tool. If everything looks alright, let move on to get some real data.
Step 7: Connect with YouTube using YouTube API V3.
Change our controller code into this:
app.controller('mycontroller', function($scope, $http){
    $scope.videos = [];

    $scope.youtubeParams = {
      key: 'YOUR YOUTUBE API KEY',
      type: 'video',
      maxResults: '5',
      part: 'id,snippet',
      q: 'YOUR SERACH KEYWORDS',
      order: 'date',
      channelId: 'YOUR CHANNEL ID',
    }

    $http.get('https://www.googleapis.com/youtube/v3/search', {params:$scope.youtubeParams}).success(function(response){
      angular.forEach(response.items, function(child){
        console.log (child);
      });
    });

  });
Please refer here to get your own YouTube API V3 Key. Also, take a look at YouTube Search API structure here: https://developers.google.com/youtube/v3/docs/search/list
We use the angular $http service here to get the data from YouTube. For more info about $http service, take a look at the official docs:https://docs.angularjs.org/api/ng/service/$http
Now open your developer console, you should see 5 objects return by YouTube. Make sure you get these 3 objects before moving forward. If you did not receive the objects or there is an error, make sure your YouTube API key is corrected and your channel ID is corrected. Also, make sure your “q” search term is not too narrow.
After successfully get the 5 objects and logged it onto the console. Change console.log (child); to $scope.videos.push(child); in order to push the data into videos array. We will use this array to display data with ng-repeat directive provided by AngularJS.
Step 8: Update the view (the index.html) using Ioinc Card to create a beautiful card display.
Update index.html like this:
<body ng-app="youtubevideo" ng-controller="mycontroller">
<ion-pane>
  <ion-header-bar class="bar-positive">
    <h1 class="title">My Video App</h1>
  </ion-header-bar>
  <ion-content>
    <div class="list card" ng-repeat="video in videos">
      <div class="item item-text-wrap">
        <h2>{{video.snippet.title}}</h2>
        <p>{{video.snippet.publishedAt | limitTo: 10}}</p>
      </div>
      <div class="item item-image">
        <img ng-src="{{video.snippet.thumbnails.high.url}}">
      </div>

    </div>
  </ion-content>
</ion-pane>
</body>
In AngularJS, we use {{ }} to display data (data binding). Video represent each video inside the data as in ng-repeat. Look at the return data from YouTube so you can find the correct path to the data you need to display onto the Ionic Card. On the featured image, we use ng-src instead of just src to make it Angular. We are loading the featured image from YouTube here. But we want to display the actual YouTube video instead so users can click and play the videos on their devices. Let’s do that next.
Step 9: Use third party library – Angular YouTube Embed to display the video.
Go to Angular YouTube Embed Github page and follow the instruction to install Angular YouTube Embed via bower
Include the necessary javascript files in your index.html and inject Angular YouTube Embed into your Angular module as dependency like so:
var app = angular.module('youtubevideo', ['ionic', 'youtube-embed']);
Inside our controller, we setup some properties for your YouTube player. Put below codes into our controller:
$scope.playerVars = {
  rel: 0,
  showinfo: 0,
  modestbranding: 0,
}
For the complete player variables, check out YouTube doc here.
Then we use the Angular YouTube Embed directive on our view (index.html) to display the video like so:
Replace <img ng-src="{{video.snippet.thumbnails.high.url}}"> to <div class=
"embed-responsive embed-responsive-16by9"><youtube-video class=
"embed-responsive-item" video-id="video.id.videoId" player-vars="playerVars"></youtube-video></div>
The first Div is for responsive video so the video will scale according to screen size. Inside youtube-video directive, we set the video-id and player-vars. Video id is returned by YouTube API V3.
We also need to put below css code into css/style.css to make the video responsive:
    .embed-responsive {
      position: relative;
      display: block;
      height: 0;
      padding: 0;
      overflow: hidden;
    }

    .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;
    }
Save all the files and review the app on your browser. You should see the YouTube video populated.

6 comments:

  1. Very interesting and creative tutorial for Hybrid app with an Ionic. These free self help blogs are so greatly appreciated!.

    Jeevitha from Way2Smile (an expert App Development Company in Chennai)

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Awesome information about topics.Graymen Technologie offers PHP Development Services are best way to increase your online business through attractive website.

    ReplyDelete
  5. Information is pretty good and impressed me a lot. This article is quite in-depth and gives a good overview of the topic. If you are looking for SIL & Functional Safety studies or DERA DUST EXPLOSION RISK ASSESSMENT than contact us.

    ReplyDelete

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...