AngularJS Demo Project: How To Build an App with AngularJS

If you’re learning full-stack development, you must’ve faced the question, “How to run AngularJS project?” Don’t worry because, in this article, we’ll share a detailed tutorial on building an app with AngularJS

After completing this project, you’d be familiar with the basics of AngularJS, its implementations, and have a working app that you can show off to your friends. You can bookmark this tutorial as we have listed out steps for different development stages along with the code. 

Note that you should understand the code before you implement it. That’s why we don’t recommend copy and pasting the code. However, if you know how every line of code works, you can freely copy and paste it. Understanding how the code works would ensure that you learn most efficiently. 

What is AngularJS? A Brief Introduction

Before we discuss AngularJS projects, let’s talk a bit about the technology first. AngularJS allows users to extend HTML for applications. It is a front-end web framework based on JavaScript. HTML lags in dynamic views for web apps, and Angular solve that problem. 

AngularJS has a thriving community of users and developers where you can ask questions and remove your confusion. Angular provides users with data binding, controllers, and many other powerful tools to enhance a web page’s front-end. You’ll discover many concepts in our project as we’ll implement them in our tutorial. 

Prerequisites to AngularJS Projects for Beginners

Before you start working on AngularJS projects, you should be familiar with the following concepts:

HTML

HTML stands for HyperText Markup Language. It is responsible for any web page structure and is the first building block for web development. You should be familiar with HTML’s syntax, its elements, and implementations before you start working on this project. 

CSS

CSS stands for Cascading Style Sheets and is the primary language for adding visuals to a web page. It’s just as important as HTML because it makes the web page look better and become more accessible. While HTML is necessary for our AngularJS project’s first stage, you’d have to add CSS to it later. That’s why you should be familiar with it before you begin working on AngularJS projects for beginners. 

JavaScript

AngularJS is based on JavaScript. Being familiar with JS syntax, code, and its implementations will simplify many technical aspects of AngularJS for you as well. Make sure that you understand the basics of JS well before you begin working on this task. 

Apart from these prerequisites, you should also be familiar with the basics of AngularJS. This project assumes that you have a working knowledge of HTML, CSS, JS, and AngularJS. Now that we’ve gotten that out of the way let’s begin.

How to Run the AngularJS Project – Tutorial

In this tutorial, we’ll build an AngularJS sports-feed app. A sports-feed app shows you statistics of a match or event. For example, you can create an app that shows the matches’ scorecard or an IPL team score table. We’ve chosen to work on a sports-feed app because it doesn’t require much back-end development. 

The HTML

We’ll first start by creating the HTML for our application. Here’s the template for our HTML code. 

<body ng-app=”F1FeederApp” ng-controller=”driversController”>

  <table>

    <thead>

      <tr><th colspan=”4″>Drivers Championship Standings</th></tr>

    </thead>

    <tbody>

      <tr ng-repeat=”driver in driversList”>

        <td>{{$index + 1}}</td>

        <td>

          <img src=”img/flags/{{driver.Driver.nationality}}.png” />

          {{driver.Driver.givenName}}&nbsp;{{driver.Driver.familyName}}

        </td>

        <td>{{driver.Constructors[0].name}}</td>

        <td>{{driver.points}}</td>

      </tr>

    </tbody>

  </table>

</body>

You must’ve noticed {{ and }}. They are called expressions, and they let you perform computational tasks for returning the required value. For example, here are some valid expressions:

  • {{ 2 + 2 }}
  • {{ my.name }}

You can say that they are snippets of JavaScript. However, it would be best if you didn’t use expressions to implement high-level logic. To do that, you should use directives. Expressions are only suitable for low-level logic implementation. The primary task of expressions is to bind the required application data to the HTML. 

Learn: HTML Developer Salary in India: For Freshers & Experienced

The Directives in Our Code

One of the most important concepts you’d discover while working on AngularJS projects is directives. A directive is a marker on a DOM element to inform AngularJS that it has to attach a specific behavior to the individual element. The directive can tell Angular to perform various tasks such as transforming the DOM element and its children, replacing it with a different DOM element. Most of the powerful directives start with “ng-” where “ng” stands for Angular. 

Here are the different directives we’ve used in our code above, along with their applications:

ng-app

This directive bootstraps the app and defines its scope. It’s an essential directive because you can have multiple apps in AngularJS, and it tells the program the starting and ending points of each app. 

ng-controller

This directive defines which controller would have the power of the user’s view. We’ve denoted the driversController in this respect, which will provide the list of drivers (driversList) in our app. 

ng-repeat

This directive is one of the most commonly used among Angular developers. It defines the template scope during the looping through collections. 

Angular has many directives, and as you’ll work on more AngularJS projects for beginners, you’ll discover more applications for them. That’s why we recommend working on different projects while learning a particular skill. 

The Controllers

Having the view would be useless unless we add a controller. So, we’ll add the driversController here:

angular.module(‘F1FeederApp.controllers’, []).

controller(‘driversController’, function($scope) {

    $scope.driversList = [

      {

          Driver: {

              givenName: ‘Sebastian’,

              familyName: ‘Vettel’

          },

          points: 322,

          nationality: “German”,

          Constructors: [

              {name: “Red Bull”}

          ]

      },

      {

          Driver: {

          givenName: ‘Fernando’,

              familyName: ‘Alonso’

          },

          points: 207,

          nationality: “Spanish”,

          Constructors: [

              {name: “Ferrari”}

          ]

      }

    ];

});

A unique variable you might’ve noticed is $scope. We’re passing this variable as a parameter to the controller as it would link the controller with views. $scope holds all the data to use in the template, and all the data you add to it will be accessible in the views. 

We’ll add a static data array for now and replace it later as we make progress in our project. 

Let’s first add the controller to the app.js, which should look like this:

angular.module(‘F1FeederApp’, [

  ‘F1FeederApp.controllers’

]);

This small line of code initialized our app and registered the modules our app depends on. We now have to add all of this information to our index.html file:

<!DOCTYPE html>

<html>

<head>

  <title>F-1 Feeder</title>

</head>

<body ng-app=”F1FeederApp” ng-controller=”driversController”>

  <table>

    <thead>

      <tr><th colspan=”4″>Drivers Championship Standings</th></tr>

    </thead>

    <tbody>

      <tr ng-repeat=”driver in driversList”>

        <td>{{$index + 1}}</td>

        <td>

          <img src=”img/flags/{{driver.Driver.nationality}}.png” />

          {{driver.Driver.givenName}}&nbsp;{{driver.Driver.familyName}}

        </td>

        <td>{{driver.Constructors[0].name}}</td>

        <td>{{driver.points}}</td>

      </tr>

    </tbody>

  </table>

  <script src=”bower_components/angular/angular.js”></script>

  <script src=”bower_components/angular-route/angular-route.js”></script>

  <script src=”js/app.js”></script>

  <script src=”js/services.js”></script>

  <script src=”js/controllers.js”></script>

</body>

</html>

At this stage, you can start your app. However, keep in mind that you will have to debug the app. A crucial step of learning how to run the AngularJS project is debugging an app.

Load Data from Server

Now we’ll add the functionality of fetching live data from a RESTful server in our app. To communicate with HTTP servers, AngularjS has two services, $http, and $resource. In our code, we’ll use $http as it offers high-level abstraction. We’ll create a custom service to abstract our server API calls. It will fetch the data and be a wrapper around $http. So, we’ll add the following code to our services.js file:

angular.module(‘F1FeederApp.services’, []).

  factory(‘ergastAPIservice’, function($http) {

    var ergastAPI = {};

    ergastAPI.getDrivers = function() {

      return $http({

        method: ‘JSONP’, 

        url: ‘http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK’

      });

    }

    return ergastAPI;

  });

We first created a new module called F1FeederApp.services and added a service ergastAPIservice. Note that we have passed $http as a parameter to the service. We will also tell Angular to add our module into the app. For doing all that, we have to replace the code in app.js with the following:

angular.module(‘F1FeederApp’, [

  ‘F1FeederApp.controllers’,

  ‘F1FeederApp.services’

]);

We’ll have to modify controller.js a little and add ergastAPIservice in the form of dependency, and then this step will finish:

angular.module(‘F1FeederApp.controllers’, []).

  controller(‘driversController’, function($scope, ergastAPIservice) {

    $scope.nameFilter = null;

    $scope.driversList = [];

    ergastAPIservice.getDrivers().success(function (response) {

        //Dig into the responde to get the relevant data

        $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;

    });

  });

To check whether the code is working or not, reload your application. You’d notice that we didn’t modify the template but only included the nameFilter variable. In the next section, we’ll use that variable:

Apply Filters

So far, we have added a functional controller to our app. Now we’ll add more functionality to it by adding a text search input bar. You can include the following code in your index.html below the <body> tag:

<input type=”text” ng-model=”nameFilter” placeholder=”Search…”/>

We are using the “ng-model” directive here. It will bind the text field to the “$scope.nameFilter” variable. The directive ensures that our variable value remains updated according to the input value. Let’s tell “ng-repeat” that it must filter the “driversList” array by the value present in the “nameFilter” before it outputs the data:

<tr ng-repeat=”driver in driversList | filter: nameFilter”>

We are performing two different data bindings here. First, whenever you’d input a value in the search field, Angular will ensure that the $scope.nameFilter variable is updated accordingly. Second, as soon as nameFilter updates ng-repeat, the second directive attached to it gets a new value and an update. 

Suppose we only want to filter by using Driver.familyName and Driver.givenName. We’ll have to add driversController below $scope.driversList = [] like this:

$scope.searchFilter = function (driver) {

    var keyword = new RegExp($scope.nameFilter, ‘i’);

    return !$scope.nameFilter || keyword.test(driver.Driver.givenName) || keyword.test(driver.Driver.familyName);

};

To finalize this process, we only have to update the line with the ng-repeat directive:

<tr ng-repeat=”driver in driversList | filter: searchFilter”>

You can reload the app to see if the code is working or not. Our app now has a search function. Next, we’ll add routes.

Adding Routes

We have to create a page that shows the details of our drivers. The page should allow a user to click on a driver and view his or her career information. We’ll begin by adding the $routeProvider service in the app.js file. It will help you handle the different application routes properly. 

Now we’ll add a route for driver information and another for the championship scoreboard. Now, our app.js file looks like this:

angular.module(‘F1FeederApp’, [

  ‘F1FeederApp.services’,

  ‘F1FeederApp.controllers’,

  ‘ngRoute’

]).

config([‘$routeProvider’, function($routeProvider) {

  $routeProvider.

when(“/drivers”, {templateUrl: “partials/drivers.html”, controller: “driversController”}).

when(“/drivers/:id”, {templateUrl: “partials/driver.html”, controller: “driverController”}).

otherwise({redirectTo: ‘/drivers’});

}]);

After adding this code, when a user would navigate to https://domain/#drivers, it will load the driversController and locate the partial view. If you’ve been following this tutorial so far, you must’ve noticed one thing. We haven’t added the partial views! So our next step would be to add the same to our application:

Adding Partial Views

A great feature of AngularJS is that it lets you bind different routes to various views and controllers. However, for AngularJS to perform this action, it should know where it can render those partial views. 

So we’re using the ng-view directive and add it to our index.html file:

<!DOCTYPE html>

<html>

<head>

  <title>F-1 Feeder</title>

</head>

<body ng-app=”F1FeederApp”>

  <ng-view></ng-view>

  <script src=”bower_components/angular/angular.js”></script>

  <script src=”bower_components/angular-route/angular-route.js”></script>

  <script src=”js/app.js”></script>

  <script src=”js/services.js”></script>

  <script src=”js/controllers.js”></script>

</body>

</html>

Due to this implementation, when we’d navigate through an app route, Angular will load the relevant view and render it. It would determine the location for rendering through the <ng-view> tag. Now, we only have to make a file called partials/drivers.html and put the championship table’s HTML code there. While we’re at it, we’ll also link our driver information route with the driver’s names:

<input type=”text” ng-model=”nameFilter” placeholder=”Search…”/>

<table>

<thead>

  <tr><th colspan=”4″>Drivers Championship Standings</th></tr>

</thead>

<tbody>

  <tr ng-repeat=”driver in driversList | filter: searchFilter”>

    <td>{{$index + 1}}</td>

    <td>

      <img src=”img/flags/{{driver.Driver.nationality}}.png” />

      <a href=”#/drivers/{{driver.Driver.driverId}}”>

{{driver.Driver.givenName}}&nbsp;{{driver.Driver.familyName}}

</a>

</td>

    <td>{{driver.Constructors[0].name}}</td>

    <td>{{driver.points}}</td>

  </tr>

</tbody>

</table>

We’re reaching the final stages of development. Our driver information page needs data so that’s what we’ll add to it. To do that, we’d have to write the following code in services.js:

angular.module(‘F1FeederApp.services’, [])

  .factory(‘ergastAPIservice’, function($http) {

    var ergastAPI = {};

    ergastAPI.getDrivers = function() {

      return $http({

        method: ‘JSONP’, 

        url: ‘http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK’

      });

    }

    ergastAPI.getDriverDetails = function(id) {

      return $http({

        method: ‘JSONP’, 

        url: ‘http://ergast.com/api/f1/2013/drivers/’+ id +’/driverStandings.json?callback=JSON_CALLBACK’

      });

    }

    ergastAPI.getDriverRaces = function(id) {

      return $http({

        method: ‘JSONP’, 

        url: ‘http://ergast.com/api/f1/2013/drivers/’+ id +’/results.json?callback=JSON_CALLBACK’

      });

    }

    return ergastAPI;

  });

We’ll now edit controllers.js. We aim to connect every driver’s ID to the service, so our information retrieval remains specific to the requested driver.

angular.module(‘F1FeederApp.controllers’, []).

  /* Drivers controller */

  controller(‘driversController’, function($scope, ergastAPIservice) {

    $scope.nameFilter = null;

    $scope.driversList = [];

    $scope.searchFilter = function (driver) {

        var re = new RegExp($scope.nameFilter, ‘i’);

        return !$scope.nameFilter || re.test(driver.Driver.givenName) || re.test(driver.Driver.familyName);

    };

    ergastAPIservice.getDrivers().success(function (response) {

        //Digging into the response to get the relevant data

        $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;

    });

  }).

  /* Driver controller */

  controller(‘driverController’, function($scope, $routeParams, ergastAPIservice) {

    $scope.id = $routeParams.id;

    $scope.races = [];

    $scope.driver = null;

    ergastAPIservice.getDriverDetails($scope.id).success(function (response) {

        $scope.driver = response.MRData.StandingsTable.StandingsLists[0].DriverStandings[0]; 

    });

    ergastAPIservice.getDriverRaces($scope.id).success(function (response) {

        $scope.races = response.MRData.RaceTable.Races; 

    }); 

  });

Note that we added the $routePrams service in the driver controller. It would let you access URL parameters and is a crucial step. 

Now we’ll create a file called partials/driver.html as we’ve added all the necessary data and only have to tackle the rest of the partial view. We’ve used the ng-show directive in the code below. The directive will ensure that our app only shows the necessary HTML element when the expression is true. This means even if the condition is null, the app wouldn’t show the HTML element. Here’s the code:

<section id=”main”>

  <a href=”./#/drivers”><- Back to drivers list</a>

  <nav id=”secondary” class=”main-nav”>

    <div class=”driver-picture”>

      <div class=”avatar”>

        <img ng-show=”driver” src=”img/drivers/{{driver.Driver.driverId}}.png” />

        <img ng-show=”driver” src=”img/flags/{{driver.Driver.nationality}}.png” /><br/>

        {{driver.Driver.givenName}} {{driver.Driver.familyName}}

      </div>

    </div>

    <div class=”driver-status”>

      Country: {{driver.Driver.nationality}} <br/>

      Team: {{driver.Constructors[0].name}}<br/>

      Birth: {{driver.Driver.dateOfBirth}}<br/>

      <a href=”{{driver.Driver.url}}” target=”_blank”>Biography</a>

    </div>

  </nav>

  <div class=”main-content”>

    <table class=”result-table”>

      <thead>

        <tr><th colspan=”5″>Formula 1 2013 Results</th></tr>

      </thead>

      <tbody>

        <tr>

          <td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>

        </tr>

        <tr ng-repeat=”race in races”>

          <td>{{race.round}}</td>

          <td><img src=”img/flags/{{race.Circuit.Location.country}}.png” />{{race.raceName}}</td>

          <td>{{race.Results[0].Constructor.name}}</td>

          <td>{{race.Results[0].grid}}</td>

          <td>{{race.Results[0].position}}</td>

        </tr>

      </tbody>

    </table>

  </div>

</section>

Final Steps (CSS)

By now, you have a properly functioning sports-feeder app. As we’ve discussed before, CSS focuses on making the webpage look attractive. So in this step, you have the independence to add CSS to your app and enhance its appearance. You can switch up fonts, change the background, add different images, or animate some transitions to improve the application’s UI. The technical sections of our project are complete. 

Checkout: Full Stack Developer Salary in India

Learn More about Development

You have now built an AngularJS app! We hope that you enjoyed this tutorial. Remember that 

Angular is quite a robust framework with many functionalities. The ones in this article were very few in comparison to the things Angular is capable of. As you’ll work on more advanced AngularJS projects, you’ll discover more of its powerful capabilities. 

If you want to learn more about full-stack development, then we recommend heading to our blog. You’ll find numerous resources on the various aspects of this field. Here are some for further reading:

On the other hand, you can also take a full-stack development course and learn from industry experts through projects, videos, and assignments. 

If you’re interested to learn more about full-stack development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Land on Your Dream Job

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
Enroll Today

Leave a comment

Your email address will not be published. Required fields are marked *

×