Understanding AngularJS in Fast-track Mode

Contents

  • Introduction
  • Breaking the surface: AngularJs Introduction
  • Data Binding: ng-model, ng-bind and expression{{}}
  • Modules
  • Controllers
  • Filters
  • Repeaters
  • Directives
  • Communicating with Servers
  • Routing
  • Out of the Box
  • End Note

Introduction

I have been working on AngularJs for quite some time and I have become amazed by the power of AngularJs. So I thought of this article to expose the power of AngularJs to you. I have tried to make this article as explanative as possible and it is written in a fast-track mode. That means it will give you a glimpse at some of the important topics of AngularJs in very less time.

AngularJS Introduction

Breaking the surface: AngularJs Introduction

surface

AngularJs is a full-featured Single-Page Application (SPA) framework. It is a JavaScript framework. It is a library written in JavaScript. It turns a simple HTML page into a full-fleged Single-Page Application by adding some custom attributes (directives, we'll see them soon). I will not waste time by adding definitions and details from the Wikipedia because our main goal is to learn most of it in less time. So the following figure is a brief description of AngularJs.

description of AngularJS

As you can see from the diagram, there is much to learn about AngularJs but we will learn some of the very important and core topics.

Before we move forward, let me tell you what we will build. We will be building a very simple Single-Page Application of a Movies App and in the building process we will be covering the following topics:

  • Data Binding
  • Controllers
  • Directives
  • Filters
  • Routing
  • Template
  • Retrieving data from Servers

Before we proceed the following is the procedure you need to follow to use AngularJs in your web application:

  1. Download the AngularJs minified JavaScript file or you can use the CDN in the HTML page. Please visit for downloading or for CDN.

  2. Load the angular.js library.
    1. ( <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js">  
    2. </script>  
    or
    1. <script src="angular.min.js"></script> )  
  3. Tell Angular which part of the DOM it should manage with the ng-app directive.

    Note: We will be doing all the preceding procedure in this article so just sit tight and let our Angular train begin.

Data Binding: ng-model, ng-bind and expression{{}}

Angular supports a Model View Controller style of application design.

  • Model: A model containing data that represents the current state of your application.

  • View: Views that display this data.

  • Controllers: Controllers that manage the relationship between your model and your views.

Data Binding

Baby Step towards Angular


towards Angular

You can use any editor of your choice to build your Angular application. For the sake of simplicity I will be using Notepad++. First create a HTML page and add a script tag and load the AngularJs library. In the body tag create a container div then add a text box and a para to it. We need to add new attributes to the div and text box that are known as directives in AngularJs. See the code below. I will explain the meaning soon.

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="utf-8" />  
  5.     </head>  
  6.     <body>  
  7.         <script src="scripts\angular.min.js"></script>  
  8.         <!--AngularJs library is loaded.-->  
  9.         <div ng-app>  
  10.             <!-- New attribute ng-app(directive) to let browser know that this div is using angular js-->  
  11.             <input type="text" ng-model="Name" />  
  12.             <!--Attribute ng-model-->  
  13.             <p>{{Name}}</p>  
  14.         </div>  
  15.     </body>  
  16. </html>  
As you can see, we have two attributes (directives). The first one is ng-app that tells the browser which part of HTML is using AngularJs and the other one is ng-model that is binding the data (Name), so whatever you type in TextBox is stored in Name and will be displayed in the para using the expression. {{}} is the syntax of an expression. We can also do it using ng-bind in our para instead of expression.
  1. <p ng-bind=”Name”></p>  
Output

angularjs

That's it. Just by adding two new attributes and without writing any script we have created a fully functional app. That's the power of AngularJs.

The following are some definitions from http://www.w3schools.com/.


  • The ng-app directive initializes an AngularJs application.

  • The ng-model directive binds the value of HTML controls (input, select, textarea) to the application data.

  • The ng-bind directive binds the application data to the HTML view.

  • AngularJs expressions bind data to HTML the same way as the ng-bind directive.

  • AngularJs expressions are much like JavaScript expressions, they can contain literals, operators and variables. Example:
    1. 1.  <p>{{5*2}}</p> Output:10   
    2. 2.  <span>{{“hello ”+ Name}}</span>   
    Output: hello [Value stored in Name].

Modules

Modules define an AngularJs application. They are a container for various parts of an application. Modules contain a special JavaScript Object called controllers that controls various parts of an application. A module can contain more than one controller as needed. Let's define our own module for our app as in the following:

  1. var app= angular.module(‘MovieApp’,[]);  
Here MovieApp is the name of our module that we will require in the HTML page to let our HTML page know which ng-app to use. The [] brackets are used for dependency injection. In simple words we can inject here the name of other modules to which our module is depended upon.
  1. <!DOCTYPE html>  
  2. <html ng-app="MovieApp">  
  3.     <head>  
  4.         <meta charset="utf-8" />  
  5.     </head>  
  6.     <body>  
  7.         <script src="scripts\angular.min.js"></script>  
  8.         <!--AngularJs library is loaded.-->  
  9.     </body>  
  10. </html>  
Controllers

Controllers are the mediator between the Model and the View. It controls the data and the Model to display on the View. We can say an AngularJs application is controlled by controllers. We can create logic to manipulate the Model in the controllers. Controllers can be classes or types we write in Angular of objects or variables make up our model by assigning them to the special object called $scope passed into our controller. Let's see a simple example:
  1. <!DOCTYPE>  
  2. <html ng-app="MovieApp">  
  3.     <!--ng-app: this is an angular app , MovieApp is the Module Name-->  
  4.     <head>  
  5.         <title></title>  
  6.     </head>  
  7.     <body>  
  8.         <script src="scripts\angular.min.js"></script>  
  9.         <!--AngularJs library is loaded.-->  
  10.         <script>  
  11. var app = angular.module("MovieApp", []);//Module created  
  12.   
  13. app.controller("MyCtrl", function ($scope)//Controller created and $scope object is passed.   
  14. {  
  15. $scope.MyModelData = "Hello, you can see me on View."// MyModelData is the model which we can access on our view.  
  16.   
  17. });  
  18. </script>  
  19.         <div ng-controller="MyCtrl">  
  20.             <!--ng-controller for this div to contol model for it.-->  
  21.             <span ng-bind="MyModelData" ></span>  
  22.             <!--MyModelData is bind here using ng-bind to display on the span-->  
  23.             <p>  
  24.                 <b>{{MyModelData}}</b>  
  25.             </p>  
  26.             <!--Expressions are used to bind MyModelData-->  
  27.         </div>  
  28.     </body>  
  29. </html>  
Controllers

Filters

Filters help us to transform/format data for display in a View for the user to make it more readable and user-friendly. The syntax for filters is:
  1. {{ expression | filterName : parameter1 : parameter2 … }}  
Some of the commonly used filters are currency, uppercase, lowercase, number and so on. You can find them all on AngularJs official website.

Let's see a live example to understand it better:
  1.            
  2. <!DOCTYPE>  
  3. <html ng-app="MovieApp">  
  4.     <!--ng-app: this is an angular app , MovieApp is the Module Name-->  
  5.     <head>  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <script src="scripts\angular.min.js"></script>  
  10.         <!--AngularJs library is loaded-->  
  11.         <script>  
  12.             var app = angular.module("MovieApp", []); //Module created  
  13.   
  14.             app.controller("MyCtrl", function ($scope)//Controller created and $scope object is passed.    
  15.             {  
  16.                 $scope.Amount = "1000.00";  
  17.                 $scope.Num = 500.000;  
  18.                 $scope.Name = "Mr. xyZ";  
  19.   
  20.             });  
  21.         </script>  
  22.         <div ng-controller="MyCtrl">  
  23.             <!--ng-controller for this div to contol model for it.-->  
  24.             <p>Amount: {{Amount | currency}}</p>  
  25.             <!--Filters used-->  
  26.             <p>Number without decimal digit:{{Num | number:0}}</p>  
  27.             <p>Number with one decimal digit: {{Num | number:1}}</p>  
  28.             <p>Number with two decimal digit: {{Num | number:2}}</p>  
  29.             <p>Name in uppercase: {{Name | uppercase}}</p>  
  30.             <p>Name in lowercase: {{Name | lowercase}}</p>  
  31.             <p></p>  
  32.         </div>  
  33.     </body>  
  34. </html>  
Output

Filters


Repeaters

Until now we saw some basic topics of Angular and now we will see possibly the most useful directive of Angular, ng-repeat, that creates a copy of a set of elements once for every item in a collection. I know you won't believe it until you see it so let's see a live example as in the following:
  1. <!DOCTYPE>  
  2. <html ng-app="MovieApp"><!--ng-app: this is an angular app , MovieApp is the Module Name-->  
  3. <head>  
  4.     <title></title>  
  5. </head>  
  6. <body>  
  7. <script src="scripts\angular.min.js"></script>  
  8. <script>  
  9.     var app = angular.module("MovieApp", []);//Module created  
  10.   
  11.     app.controller("MyCtrl", function ($scope)//Controller craeted and $scope object is passed.    
  12.     {  
  13.         $scope.Movies = [  
  14.         {MovieName:"The Dark Knight", Rating : 8.4},  
  15.         {MovieName:"Dark Knight Rises", Rating : 8.1},  
  16.         {MovieName:"The Fight Club", Rating : 8.3},  
  17.         { MovieName: "Mad Max Fury", Rating: 8.2 },  
  18.         { MovieName: "Warrior", Rating: 8.4 }  
  19.         ];  
  20.   
  21.     });  
  22. </script>  
  23. <div ng-controller="MyCtrl"><!--ng-controller for this div to contol model for it.-->  
  24.   
  25. <ul ng-repeat="mov in Movies"><!--ng-repeat is used to loop for items in Movies object-->  
  26. <li>{{mov.MovieName}}</li><!--Only one li item is created here but at run 5 li will be created-->  
  27. </ul>  
  28.   
  29. <!--ng-repeat for tables-->  
  30. <table border="1">  
  31. <thead>  
  32. <tr>  
  33. <th>Name</th><th>Ratings</th>  
  34. </tr>  
  35. </thead>  
  36. <tbody>  
  37. <tr ng-repeat=  "mov in Movies"><!--Only one row is created here but rest will created automatically-->  
  38. <td>{{mov.MovieName | uppercase}}</td>  
  39. <td>{{mov.Rating}}</td>  
  40. </tr>  
  41. </tbody>  
  42. </table>  
  43.   
  44. </div>  
  45. </body>  
  46. </html>  
Output

Output

The preceding code is self-explanatory but let me clarify it for you. As you can see the <ul> loops through all the items and creates a <li> for each item present in the object. The same thing happened in the table, the <tr> looped through all the items and rows will be created at runtime.

Directives

With directives we can extend the HTML syntax, we can create our custom elements and attributes to associate the behavior and DOM transformations. We can create reusable UI components and templates that suits our application needs. In fact, until now we have used Angular's built-in directives with the ng-directive-name syntax. Examples include ng-model, ng-repeat, ng-controller, ng-app. Here ng is the namespace for Angular and the part after the dash is the name of the directive.

Well enough talk, let's create our own simple directive or usable component as in the following:
  1. <!DOCTYPE>  
  2.      <html ng-app="MovieApp"><!--ng-app: this is an angular app , MovieApp is the Module Name-->  
  3.      <head>  
  4.          <title></title>  
  5.      </head>  
  6.      <body>  
  7.      <script src="scripts\angular.min.js"></script>  
  8.      <script>  
  9.          var app = angular.module("MovieApp", []);//Module created  
  10.   
  11.          app.directive("banner", function () { //Directive created   
  12.   
  13.              return {  
  14.   
  15.                  restrict: 'E',  
  16.                  template: '<h1>Hello World!!</h1><h2>My first Directive</h2>',  
  17.                  link: function (scope,element,attribute) {  
  18.                      element.bind("mouseenter", function () { alert("Hi, there!!") })  
  19.                  }  
  20.   
  21.              }  
  22.   
  23.          });  
  24.      </script>  
  25.      <div >  
  26.      <banner></banner><!--Directive implemented-->  
  27.      </div>  
  28.      </body>  
  29.      </html>  
Output

hello word

Let's see the property used to build our directive.

Restrict

Restrict specifies how the directive will be used in a template as an element (E), attribute (A), class (C) or comment (M). In our example we created an element by setting the restrict property to "E". So we can create our custom attribute, class and comment for HTML elements.

Template

Template specifies an inline template as a string. We have added two heading tags.

Link

A Link programmatically modifis the DOM element instances and adds event listeners and sets up data binding.

Here we have created a very simple usable template called banner element that contains two headings, <h1> and <h2>. If you inspect an element tehn you can easily determine the <banner> tag. The interesting thing is that here <banner> is not an actual HTML tag but still your browser is showing the output. If you want to hide the <banner> tag and just want to show the <h1> and <h2>, you can also do that by just adding one more property to your directive, "replace : true". We have also linked a function to our directive that takes the three parameters, the scope of that directive, the element that is our directive and the attribute of our directive. In this function we have bound the mouseenter event to our element and on mouseenter it gives an alert.

We have used only three properties in our directive but they are not limited to three, there are more properties that we can use for making our custom directive. But unfortunately we are not explaining them in this article because it's just an introduction article and I don't want to make things complicated here but maybe in the future I will return with another article explaining all that we have left here.

Communicating with Servers

Nearly every app needs to communicate with a server to fetch some data or to post some data. For this Angular provides a service called $http. It provides abstraction that makes it easier to talk to servers. Let's say we need to retrieve a movies list for our app from a server instead of from variables or in-memory mocks. So all we need is the service that can provide the movie list in JSON format when we query Angular. Since we do not have such a service we will retrieve our data from a JSON file in our app. Here I am just showing you the syntax for using $http, we will see a complete example when we start building our app.
  1. $http.get(ServiceURL).success(function (data, status, headers, config) {  
  2.   
  3.    // do something with data  
  4.   
  5. });  
The preceding is very simple syntax to get data from a server.

Routing

In a Single-Page Application, the HTML page is loaded on the first request, then only some areas within the DOM are updated. In a SPA we usually have multiple sub-page views or templates that we show or hide from the user appropriately. For this in Angular we have $route to handle such scenarios. Using $route we specify that, for a given URL that the browser points to, Angular should load and display a template and instantiate a controller to provide context for the template.

We can create routes in our app using the $routeProvider service as a configuration block for an Angular module in our application.

Let's quickly see its syntax as in the following:
  1. app.config(function ($routeProvider) {  
  2.          $routeProvider.  
  3.      when('/', {  
  4.          templateUrl: 'path of html',  
  5.          controller: 'AppCtrl'  
  6.   
  7.      }).  
  8.      when('/first', {  
  9.          templateUrl: 'path of template 1 html',  
  10.          controller: 'Ctrl1'  
  11.      }).  
  12.      when('/second', {  
  13.          templateUrl: 'path of template 2 html',  
  14.          controller: 'Ctrl2'  
  15.      }).  
  16.      otherwise({  
  17.          redirectTo: '/'  
  18.      });  
  19.   
  20.   
  21. });  
The syntax is much easier here when the browser points to "/". The main HTML page is loaded and the controller "AppCtrl" is loaded and when the browser points to "/first" the HTML page containing template 1 is loaded into the main page in the <ng-view></ng-view> directive defined on the page. I know at this point it's kind of hard to understand without an example but don't worry, for now just concentrate on the syntax, we will be seeing soon the working example of it.

Out of the Box

As I promised here, we are ready to create our first AngularJs app. I will be using all the concepts that we have discussed above. Since this will be our first app I have tried to make things as simple as possible. We will be creating a movie app that will show the names of movies in a table and you can determine more about any movie by clicking on its name.

Out of the Box

The following is the screen-shot of what we will build:

build

app

The following is the folder structure of our app:

structure of our app

Step 1: index.html

Create a HTML page named it index.html. Link CSS file. Load the AngularJs Library. I have used two files to load the library, one is angular.min.js and the other is angular-route.js that we will require for routing. Also load our app script file. Add an attribute to the ng-app=”MovieA” that we tell the browser that this page is an Angular app. This page is very simple, nothing is in it except for the logo div and our custom directive <banner> and the <ng-view> directive of Angular.
  1. <!DOCTYPE html>  
  2. <html ng-app="MovieApp">  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title>AngularJS Movies App</title>  
  6.     <link href="css\Style.css" rel="stylesheet" />  
  7. </head>  
  8. <body>  
  9.     <script src="scripts\angular.min.js"></script>  
  10.     <script src="scripts\angular-route.js"></script>  
  11.     <script src="scripts\script.js"></script>  
  12.     <div>  
  13.         <!---Logo div of our app-->  
  14.         <div class="header">  
  15.             <img src="img\logo.png" style="width: 200px;" />  
  16.         </div>  
  17.   
  18.         <!--Custom directive-->  
  19.         <banner></banner>  
  20.   
  21.         <!--ng-view to load different templates here using routing-->  
  22.         <ng-view></ng-view>  
  23.   
  24.     </div>  
  25. </body>  
  26. </html>  
Step 2: style.css

The CSS is also very simple. I hope you will understand it easily.
  1. body {  
  2. color: #204056;  
  3. }  
  4.   
  5. a {  
  6.     color: #204056;  
  7. }  
  8. .header {  
  9.     width: 100%;  
  10.   background-color: #39d1b4;  
  11.   height: 50px;  
  12.   padding: 0px;  
  13.   margin: 0px;  
  14. }  
  15.   
  16. h2{  
  17. margin-left:40%;  
  18. }  
  19. h3 {  
  20. margin-left:38%;  
  21. }  
  22.   
  23. .myborder  
  24. {  
  25. border-radius: 18px 17px 14px 21px;  
  26. border: 5px solid #39D1B4;  
  27. }  
  28.   
  29. p  
  30. {  
  31. margin-left: 14px;  
  32. font-family: "Comic Sans MS",Arial,Helvetica,sans-serif;  
  33.   
  34. }  
  35.   
  36. span  
  37. {  
  38. color: #0066FF;  
  39. font-size: 1.3em;  
  40. }  
  41. #movies {  
  42.     margin-top:5px;  
  43.     font-family: "Comic Sans MS", Arial, Helvetica, sans-serif;  
  44.     width: 100%;  
  45.     border-collapse: collapse;  
  46. }  
  47.  
  48. #movies td, #movies th {  
  49.     font-size: 1em;  
  50.     border: 1px solid #204056;  
  51.     padding: 3px 7px 2px 7px;  
  52. }  
  53.  
  54. #movies th {  
  55.     font-size: 1.1em;  
  56.     text-align: left;  
  57.     padding-top: 5px;  
  58.     padding-bottom: 4px;  
  59.     background-color: #39d1b4;  
  60.     color: #ffffff;  
  61. }  
  62.  
  63. #movies tr.alt td {  
  64.     color: #000000;  
  65.     background-color: #C4F1E8;  
  66. }  
Step 3: script.js

Let's first create a module for our app.
  1. var app = angular.module('MovieApp', ['ngRoute']);  
ngRoute is injected here for routing.

Then create our custom directive <banner>.
  1. app.directive("banner", function () {  
  2.     return {  
  3.         restrict: 'E',  
  4.         template: '<h2>AngularJS is fun!!</h2> <h3>HTML enhanced for web apps!</h3>',  
  5.   
  6.     }  
  7.   
  8. })  
Then the config of the app is defined for the routing for the various HTML templates are done. The point to see here is that when defining the route for movie.html we have passed the parameter :movieName, we will pass the value of it depending upon the movie name. The routing is very simple, when the browser points to "/" then movielist.html and its controller MoviesCtrl is loaded and when the browser points to "/movie/:movieName" then movie.html and MovCtrl are loaded.
  1. app.config(function ($routeProvider) {  
  2.     $routeProvider.when('/',  
  3.     {  
  4.         templateUrl: 'partials/part1/movieslist.html',  
  5.         controller: 'MoviesCtrl'  
  6.     })  
  7.     .when('/movie/:movieName',  
  8.     {  
  9.         templateUrl: 'partials/part2/movie.html',  
  10.         controller: 'MovCtrl'  
  11.     })  
  12. });  
So let's create a Controller for movielist.html. In this Controller we have passed $scope, $http and $location objects as parameters. $scope binds the data from the View, $http gets the data from the server (in our case it is from a JSON file), $location changes the URL in the browser.

The $http.get method is loading the data from the JSON file and filling in the movielist array.

We have also created a method $scope.redirectTo that takes the movie name as an argument and passes it to the $location.path that will change the URL in the browser and hence the template (movie.html) is loaded.
  1. app.controller('MoviesCtrl', function ($scope, $http, $location) {  
  2.     $scope.movieslist = [];  
  3.     $http.get('data/movies.json').success(function (data) {  
  4.   
  5.         $scope.movieslist = data;  
  6.   
  7.     });  
  8.     $scope.redirectTo = function (movieName) {  
  9.         $location.path('/movie/' + movieName);  
  10.   
  11.     }  
  12. });  
Another controller is for movie.html. Let's create it too. The same parameters are passed as the previous one. The array $scope.movie is created. We will grab the movie name from the URL in the browser using $location.path, find the last index of "/" and then substring the movie name from the URL.
  1. var title = $location.path().substring($location.path().lastIndexOf('/')+1);  
Again data is fetched from the JSON file but this time we will only fill the array with specific movie data, I mean the data of that movie of the title extracted from the URL. When the array is filled we will use $scope to bind the data from the View. We are iterating the objects fetched from the JSON file and check if the title of the object (movie) matches, if it matches then we put it into the array.
  1. app.controller('MovCtrl', function ($scope, $http, $location) {  
  2.     $scope.movie = [];  
  3.     var title = $location.path().substring($location.path().lastIndexOf('/') + 1); // substring the movie name  
  4.       
  5.     $http.get('data/movies.json').success(function (data) {  
  6.   
  7.         angular.forEach(data, function (array) { //iterating to check if the title matches or not  
  8.             if (array["Title"] == title) {  
  9.                 $scope.movie = array;  
  10.             }  
  11.   
  12.         });  
  13.         $scope.Title = $scope.movie["Title"];  
  14.         $scope.Year = $scope.movie["Year"];  
  15.         $scope.Released = $scope.movie["Released"];  
  16.         $scope.Runtime = $scope.movie["Runtime"];  
  17.         $scope.Actors = $scope.movie["Actors"];  
  18.         $scope.Director = $scope.movie["Director"];  
  19.         $scope.Plot = $scope.movie["Plot"];  
  20.         $scope.Genre = $scope.movie["Genre"];  
  21.         $scope.Writer = $scope.movie["Writer"];  
  22.         $scope.Awards = $scope.movie["Awards"];  
  23.         $scope.Language = $scope.movie["Language"];  
  24.         $scope.imdbVotes = $scope.movie["imdbVotes"];  
  25.         $scope.imdbRating = $scope.movie["imdbRating"];  
  26.   
  27.     });  
  28.   
  29. });  
The following is the complete script of our script.js:
  1. var app = angular.module('MovieApp', ['ngRoute']);  
  2.   
  3. ///////////////////////////////////////////////////  
  4.   
  5. //-------------Custom Directive-------------------  
  6. app.directive("banner", function () {  
  7.     return {  
  8.         restrict: 'E',  
  9.         template: '<h2>AngularJS is fun!!</h2> <h3>HTML enhanced for web apps!</h3>',  
  10.   
  11.     }  
  12.   
  13. })  
  14.   
  15. ////////////////////////////////////////////////////////////  
  16.   
  17. //-----------------Routing------------------------------  
  18. app.config(function ($routeProvider) {  
  19.     $routeProvider.when('/',  
  20.     {  
  21.         templateUrl: 'partials/part1/movieslist.html',  
  22.         controller: 'MoviesCtrl'  
  23.     })  
  24.     .when('/movie/:movieName',  
  25.     {  
  26.         templateUrl: 'partials/part2/movie.html',  
  27.         controller: 'MovCtrl'  
  28.     })  
  29. });  
  30.   
  31.   
  32.   
  33. /////////////////////////////////////////////  
  34.   
  35. //---------------------Controller for movielist html----------  
  36. app.controller('MoviesCtrl', function ($scope, $http, $location) {  
  37.     $scope.movieslist = [];  
  38.     $http.get('data/movies.json').success(function (data) {  
  39.   
  40.         $scope.movieslist = data;  
  41.   
  42.     });  
  43.     $scope.redirectTo = function (movieName) {  
  44.         $location.path('/movie/' + movieName);  
  45.   
  46.     }  
  47. });  
  48.   
  49. //////////////////////////////////////////////////////  
  50.   
  51. //---------------------Controller for movie html----------  
  52. app.controller('MovCtrl', function ($scope, $http, $location) {  
  53.     $scope.movie = [];  
  54.     var title = $location.path().substring($location.path().lastIndexOf('/') + 1); // substring the movie name  
  55.       
  56.     $http.get('data/movies.json').success(function (data) {  
  57.   
  58.         angular.forEach(data, function (array) { //iterating to check if the title matches or not  
  59.             if (array["Title"] == title) {  
  60.                 $scope.movie = array;  
  61.             }  
  62.   
  63.         });  
  64.         // binding data to display on the view  
  65.         $scope.Title = $scope.movie["Title"];   
  66.         $scope.Year = $scope.movie["Year"];  
  67.         $scope.Released = $scope.movie["Released"];  
  68.         $scope.Runtime = $scope.movie["Runtime"];  
  69.         $scope.Actors = $scope.movie["Actors"];  
  70.         $scope.Director = $scope.movie["Director"];  
  71.         $scope.Plot = $scope.movie["Plot"];  
  72.         $scope.Genre = $scope.movie["Genre"];  
  73.         $scope.Writer = $scope.movie["Writer"];  
  74.         $scope.Awards = $scope.movie["Awards"];  
  75.         $scope.Language = $scope.movie["Language"];  
  76.         $scope.imdbVotes = $scope.movie["imdbVotes"];  
  77.         $scope.imdbRating = $scope.movie["imdbRating"];  
  78.   
  79.     });  
  80.   
  81. });  
Step 4: Templates

Let's create templates that will be loaded on our index.html. Create a div and define its attribute ng-controller. Add an input box and set its ng-model to "mov" that will filter the name of the movie. Add a table, ng-repeat is used to create rows automatically based on the object on the movieslist array. We have also used ng-class to add a CSS style if the row is odd using $even.
  1. <div ng-controller="MoviesCtrl">  
  2.     <input type="text" ng-model="mov" style="width:300px;" placeholder="Search" />  
  3.     <img src="img\srch.png" style="width:15px;height:15px;" />  
  4.     <br />  
  5.     <table id="movies">  
  6.         <thead>  
  7.             <tr>  
  8.                 <th>Movies Name</th>  
  9.                 <th>Year</th>  
  10.                 <th>Genre</th>  
  11.                 <th>Rating</th>  
  12.             </tr>  
  13.         </thead>  
  14.         <tbody>  
  15.             <tr ng-repeat="t in movieslist| filter:mov " ng-class="$even ? '' : 'alt'">  
  16.                 <td><a href='' ng-click='redirectTo(t.Title)'>{{t.Title}} </a></td>  
  17.                 <td>{{t.Year}}</td>  
  18.                 <td>{{t.Genre}}</td>  
  19.                 <td>{{t.imdbRating}}</td>  
  20.   
  21.             </tr>  
  22.         </tbody>  
  23.     </table>  
  24.   
  25.   
  26. </div>  
Now create a second template that will display the complete information of a specific movie selected by the user from the list of movies table. Its a simple HTML template containing div, paras and span to display movie information but an important point here is that all the paras are bound to the model using an expression.
  1. <div class="myborder">  
  2.     <p><span>Title:</span>  {{Title}}</p>  
  3.     <p><span>Year:</span> {{Year}}</p>  
  4.     <p><span>Released:</span> {{Released}}</p>  
  5.     <p><span>Runtime:</span>{{Runtime}}</p>  
  6.     <p><span>Genre:</span>{{Genre}}</p>  
  7.     <p><span>Actors:</span> {{Actors}}</p>  
  8.     <p><span>Director:</span> {{Director}}</p>  
  9.     <p><span>Writer:</span>  {{Writer}}</p>  
  10.     <p><span>Awards:</span>  {{Awards}}</p>  
  11.     <p><span>Language:</span>  {{Language}}</p>  
  12.     <p><span>Votes:</span>  {{imdbVotes}}</p>  
  13.     <p><span>Rating:</span>  {{imdbRating}}</p>  
  14. </div>  
That's it! We are good to go now. Run index.html in a Firefox Mozilla browser because in Chrome you may get a cross-domain error or you can host the app on IIS and test it on any browser.

End Note

We created a simple app by writing very few lines of script and HTML. I hope my effort to expose the power of AngularJs helps to understand it better and you can use it for your personal or corporate apps.

 


Similar Articles