Learn Angular JS 1 Fundamentals by Doing Sample Project

If you are looking for some quick Angular JS 1 fundamentals that help you build mobiles apps, you are on right place. We are building a simple app that will fetch some data from Cinemalytics API. This way, you will get the practical use of angularjs.  Here is the link to our finished project Search Bollywood Movies by Year.

Prerequisites:  You should have a basic understanding of JavaScript, HTML, CSS and any text editor.  If you still follow along with this, it’s ok.

Angular Setup:

Make an angular setup where you can test leaning, it will be easier for you to follow with this tutorial.

  1. Create a folder name it as angularLearning
  2. To get started download angularjs . We are downloading version 1.5. Save the js file in your application folder angularLearning. Create another lib folder inside this. Cut paste angular.min.js in this directory.angular-download-1-5
  3. Download bootstrap, we are not focusing on design part that is why we are simply adding readymade design from bootstrap. Copy css and fonts folder to our application folder.
  4. Create index.html file put below code. (copy code)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Search Bollywood Movies by Year</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom -->
    <link href="css/style.css" rel="stylesheet">
    
    
    <!-- Include Angular application js -->
    <script src="lib/angular.min.js"></script>
    <script src="lib/angular-route.min.js"></script>

    <!-- Include our application js -->
    <script src="js/app.js"></script>

  </head>
  <body> 
  <!--/.Copyright link -->
  <div class="container">
      Bollywood Database Credits: <a href="https://www.cinemalytics.com" target="_blank">Cinemalytics - The Bollywood Movie Database</a>
  </div>
  </body>
</html>

Folder structure:
file-structure
You are now ready to work on angular or download angular ready setup here from GitHub.

Technical jargon we are going to use are below.

module
Angular Application is made of single or many modules. Module is a container where all your controller, routes, config, views, factory, services are added. Don’t worry right now what these are.

Directives are custom attributes define by angular in HTML. Examples are ng-click, ng-show, ng-hide, ng-view and ng-repeat so on…

Routes are nothing but just URL.

Factories or Services are reusable function in angular which can be used in controller by adding dependency.

Controllers are the function which allow us to perform certain action in the views.

Views contain html templates.

Let’s begin project

Add Module

<!-- Include Angular application js -->
    <!-- Include Angular application js -->
    <script src="lib/angular.min.js"></script>
    <script src="lib/angular-route.min.js"></script>

    <!-- Include our application js -->
    <script src="js/app.js"></script>

We have already included two files angular.min.js, angular-route.min.js in index.html from lib folder.  Now create empty js file name it app.js , include this to index as well after angular js files included. This js is going to hold our application logics.

Add very first module in app.js. Name of the module is “myApp”.

var app = angular.module('myApp', []);

In array we add dependency module. Keep it empty for time being.  Since we have created our module we need to mention this in our index.html file so that it will know what to do. In body tag add directives as ng-app=”myApp”.

<body ng-app="myApp">

Add View

To show the data to the front end, add another directive ng-view  or add class ng-view both are same.

  <div class="container">
      <div class="ng-view"></div>
  </div>

We have not defined views yet, let create it. In application config setting. $routeProvider is the dependency need to add under config setting so that we can add views and define controller for that particular view. Since we are using route we need to add dependency to our myApp module “ngRoute”.

var app = angular.module('myApp', ["ngRoute"]); 
// routes
app.config(function($routeProvider) {
$routeProvider
.when("/year/:year", {
templateUrl : "template/main.html",
controller : "allMovie"
})
.when("/id/:ID", {
templateUrl : "template/single.html",
controller : "singleMovie"
})
.otherwise( { redirectTo: '/year/2016' } );
});

HTML Template and controller will execute respectively by going to the url. If URL is not as per our defined one, then URL in otherwise function will execute that is /year/2016. Please note we have not yet created both templates controllers yet.

Add factory function

We can define reusable functions in factory function which return objects. Use this function in controller as many times as required. This will reduce the amount of time we code repetitively in controller. Name of the function is GetData. Add $http dependency core service,so that we can pass the url and get response. we have added custom function movieData which require type, passdata, and response. Both the type and passdata are just url keywords, we are replacing dynamically.
Add below code in app.js file.

// factory
app.factory('GetData', function ($http) {
  return {
    movieData: function (type,passdata, response) {
        var urlLink = "https://api.cinemalytics.com/v1/movie/" + type + "/" + passdata + "/?auth_token=1EFAE82FE7F4F8E6813FD4FA429E5170";
        $http.get(urlLink).success(response);
    }
  }
});

Add Controller

This is where you work most of your time. Two controller(allMovie, singleMovie) has been defined in route setting previously.
In controller function, first parameter is for name, second for callback function. We are adding service dependency as $scope, GetData, $routeParams, $route and $location.
$scope sevice hold data which can be used in html template to display data. Here we are storing year and movie data and two function gotoMovie , gotoMovieYear in $scope service. $routeParams give the ability to take url parameter value which we are passing in URL. $location service is related to URL again, we can redirect to any url using path function.
Add below Code in app.js file.

// controller
app.controller('allMovie', function($scope, GetData, $routeParams, $location) {
    // get year value from route parameter
    $scope.year = $routeParams.year ;
   
    // get movie data from url
    GetData.movieData('year',$routeParams.year,function(response) {
      $scope.movie = response;      
    });

    // redirect to id page
    $scope.gotoMovie = function(id){
        $location.path( "/id/" + id );
    }; 

    // redirect to year page
    $scope.gotoMovieYear = function(year){
        $location.path( "/year/" + year );
    };     
}); 

// controller
app.controller('singleMovie', function($scope, GetData, $routeParams) {
    // get movie data from url
    GetData.movieData('id', $routeParams.ID,function(response) {
        $scope.movie = response;
    });

});

Whole code in app.js will look like this

var app = angular.module('myApp', ["ngRoute"]); 

// factory
app.factory('GetData', function ($http) {
  return {
    movieData: function (type,passdata, response) {
        var urlLink = "https://api.cinemalytics.com/v1/movie/" + type + "/" + passdata + "/?auth_token=1EFAE82FE7F4F8E6813FD4FA429E5170";
        $http.get(urlLink).success(response);
    }
  }
});

// controller
app.controller('allMovie', function($scope, GetData, $routeParams, $route, $location) {

    $scope.year = $routeParams.year ;

    GetData.movieData('year',$routeParams.year,function(response) {
      $scope.movie = response;      
    });

    // redirect to page
    $scope.gotoMovie = function(id){
        $location.path( "/id/" + id );
    }; 

    // redirect to page
    $scope.gotoMovieYear = function(year){
        $location.path( "/year/" + year );
    }; 

    
}); 

// controller
app.controller('singleMovie', function($scope, GetData, $routeParams) {
    GetData.movieData('id', $routeParams.ID,function(response) {
        $scope.movie = response;
    });

});

// routes
app.config(function($routeProvider) {
    $routeProvider
    .when("/year/:year", {
        templateUrl : "template/main.html",
        controller : "allMovie"
    })
    .when("/id/:ID", {
        templateUrl : "template/single.html", 
        controller : "singleMovie"
    })
    .otherwise( { redirectTo: '/year/2016' } );
});

Add HTML Template

As the name suggest, all html markup can be added here. Two views we have defined in route setting as templateUrl. Now it’s time to add html.
ng-repeat=”amovie in movie”, this works as loop. Response is added into variable movie scope. Use express like {{amovie.PosterPath}} to get the data stored in it. ng-click directive is used to perform function scope declared in controller. To get Image url or link url dynamically always use ng-src or ng-href in case of link. ng-hide is used to hide the markup tags depends on value passed in ng-hide directive. We have added condition in ng-hide as ng-hide=”movie.Runtime==0″, if runtime value is 0, then it will hide the mark up. It also accept true or false value in it. In expression like {{movie.Title}} dot notation is used to get the json data according to key(Title).

Add this code in main.html inside template folder.

<div class="row" >
	<div class="col-lg-12 col-lg-12" >
		 	<form class="form-inline">
			  <div class="form-group">
			    <label for="year">Search Movie by Year:</label>
			    <input type="text" class="form-control" id="year" ng-model="movieyear" placeholder="Please type year">
			  </div>
			  <button type="submit" class="btn btn-default" ng-click="gotoMovieYear(movieyear)">Submit</button>
			</form><br>	  
			<h1>{{year}}</h1>	
	</div>
	<div class="col-lg-3 col-lg-3" ng-repeat="amovie in movie">
	   <img ng-src="{{amovie.PosterPath}}" alt="" ng-click="gotoMovie(amovie.Id)" class="show-cursor">	
	</div>
</div>

Add this code in single.html inside template folder.

<div class="row">
   <div class="col-lg-12">
      <h1>{{movie.Title}}</h1>
      <p>Description: {{movie.Description}}</p>
      <p>Genre: {{movie.Genre}}</p>
      <p ng-hide="movie.Runtime==0">Runtime:{{movie.Runtime}}</p> 
      <a ng-href="{{movie.TrailerLink}}" target="_blank"><img ng-src="{{movie.PosterPath}}" alt=""></a>
   </div>
</div>

Now open your index.html in browser , your application is ready.
Thanks for reading this post, post your comment below for any query.

Post Author: sachinw68