AngularJS Web Application Development Blueprints

2.3 (3 reviews total)
By Vinci Rufus
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to AngularJS and the Single Page Application

About this book

This book is a practical guide that aims to help you learn how to utilize AngularJS and experience the joy of building full-fledged applications with minimal code in no time at all.

The book starts by explaining the basics of AngularJS and helps you get comfortable with the terms and concepts surrounding it. It then walks you through the various tools, frameworks, and workflows that will help you be more productive. As you go through the book, you will learn how to build applications spanning various realms. You will build social apps using publically available APIs and responsive, mobile- and tablet-friendly personal finance applications. You will see how to build a full-stack content management system, and build an e-commerce application on the cloud platform. Finally, this book will teach you the intricacies of what it takes to get your application deployed on a production server.

 

Publication date:
August 2014
Publisher
Packt
Pages
300
ISBN
9781783285617

 

Chapter 1. Introduction to AngularJS and the Single Page Application

In this chapter, we'll learn what Single Page Apps are and how they differ from the regular web applications. We will also learn the fundamentals of AngularJS and go about building a simple Address Book App using it.

The list of topics to be covered in the chapter are as follows:

  • What are Single Page Apps?

  • Anatomy of an app

  • Models and views

  • Building an Address Book App

  • Styling the app with CSS

  • Adding items to the Address Book

 

Delving into Single Page Apps


Besides other things, AngularJS is primarily used to build Single Page Apps (SPAs), so let us first understand its characteristics.

Single Page Apps are apps or websites wherein the entire site or app content loads within a single page. This essentially means that once the app or website is loaded in the browser, clicking on any link would not reload the entire page but would simply update certain sections within the main page itself. This gives users a very desktop-like feel while using an SPA.

Although SPAs have become very popular nowadays, the concept has been discussed as early as 2003, and the term Single Page App was coined in 2005.

Some of the technologies that play a predominant role in building SPAs are HTML, CSS, JavaScript, AJAX, and web services usually RESTful. Of these, JavaScript plays the most crucial role in building an SPA, so if you have been procrastinating on sharpening your JavaScript skills this would be the best time to get up and get started.

One of the fundamental differences in the way SPAs work against regular websites is the way the pages are built, which the user sees. Refer to the following diagram:

In traditional web applications that are built on the server-side technologies such as Java, PHP, and .NET, whenever a page is requested, the web server would make a request to the database, fetch the result of the query, then load the template, and dynamically generate the final page, which is sent down to the browser. As you can see here, the web server is doing all the heavy lifting, and as the traffic to the server increases, the web server becomes a bottleneck. This is why popular high-traffic sites need a lot of servers.

Single Page Apps, especially those built on JavaScript frameworks such as AngularJS work in a slightly different fashion. Refer to the following diagram:

In an SPA architecture, the entire template along with the HTML, JavaScript, and CSS is downloaded to the user's browser, so when a request is made, content is sent from the web server and the page is built on the client side on the user's browser. Here, the browser is doing the heavy lifting. In such an architecture, the web server is merely passing raw data and is not involved in building the pages. The pages are built on each user's browser and hence even if the traffic to the site increases, the server doesn't get overloaded, as it would have in a regular web app architecture.

Another thing that makes SPAs wonderful is that the presentation layer can be completely decoupled from the backend layer.

 

Anatomy of a simple AngularJS app


Perform the following steps:

  1. To start, let's first download a version of AngularJS from http:www.angularjs.org.

  2. Click on the Download button and select the following options from the pop-up window:

    • Branch: Select Stable

    • Build: Select Minified

  3. Download the JS file and place it in your project's folder.

Let us start by writing a simple AngularJS app. Create an index.html file with the following code:

<!DOCTYPE html>
<html>
<head>
    <title>AngularJS Basic</title>
</head>

<body ng-app ng-init=" myName ='John Doe' ">
    {{myName}} is {{ 2014-1968}} years old.
    <script src=" angular.min.js " type="text/javascript "> </script>
   </body>
</html>

This is a regular HTML page with the HTML5 doctype and the AngularJS JavaScript file being called in. Now, let us look at specific syntaxes of AngularJS and what they mean. The syntaxes are as follows:

  • ng-app: This defines the element within which AngularJS will bootstrap itself. In most cases, we would add it to the <html> or <body> tag. It is also possible you would be building a regular application in Java, PHP, or .NET and only a section of it would be running an AngularJS app, in such cases you would add ng-app to the <div> tag wrapping the app component.

  • ng-init: This is used to define the initialization tasks. In this example, we are creating a model called myName with the value John Doe.

    Note

    Using ng-init is not recommended for production apps. As we will see later in this chapter, the ideal way to initialize the variable would be in the controller instead of directly writing it in the view.

  • {{ }}: The double curly brackets are used to output the data stored in models. In this case, {{myName}} outputs the value John Doe. These curly brackets can also be used for expressions, as in the example {{2014-1968}} outputs the result 46. This is very similar to how other templating engines such as Mustache or Smarty work.

  • Directives: The ng-app and the ng-init tags that you see in the preceding sample code are called Directives. They are an integral part of any AngularJS app and it is through these directives that AngularJS is able to modify the DOM element of an application. AngularJS comes with a whole set of predefined directives many of which we will use as we go through this book. The good thing about AngularJS is that you can also create your own custom directives that can meet your specific requirements.

 

Models and views


In AngularJS, a model could be a primitive, a hash table, or a JavaScript object. The data from the model can be displayed in the view using the {{ }} expression.

Models can be defined in multiple ways. Like we saw in the first example, we can define the model within the ng-init directive. It can be created in the template within the expression as follows:

<button ng-click="firstName='John Doe' ">click </button>

Alternatively, it could also be created within a controller using the scope, which is the ideal way to do it. Refer to the following code:

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Model in Scope</title>
</head>
<body ng-controller="PeopleController">
    {{person.name}} lives in {{person.city}}
    <script src="angular.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    function PeopleController($scope) {
        $scope.person = {
            name: "John Doe",
            city: "New York"
        }
    }
    </script>
</body>
</html>

In the preceding example, we created a controller called PeopleController and defined the model person, which is storing the data as a hash table. The $scope is an AngularJS object that is able to reference the JavaScript object model as a property.

 

Building an Address Book App


In the earlier examples, we saw the different ways of creating models. When creating production grade or large-scale applications, which involve graphical interfaces, it is compulsory to follow the Model View Controller (MVC) design pattern.

Building on the previous code example, we'll go ahead and build a simple Address Book App.

Let's start by creating our models in a controller called PeopleController. We'll now write all our JavaScripts in a file called scripts.js. Your scripts.js file should look like this:

function PeopleController($scope){
$scope.people=[
   {name:"John Doe", phone: "3452345678", city:"New York"},
   {name:"Sarah Parker", phone: "1236548769", city:"Chicago"},
   {name:"Little John", phone: "4567853432", city:"Los Angeles"},
   {name:"Adam Doe", phone: "9025673152", city:"Las Vegas"}
         ];
}

Here we are defining the controller called PeopleController and creating our model called people. The model contains three attributes: name, phone, and city.

Now, let us get our markup in place. Let us call the file index.html using the following code:

<!DOCTYPE html>
<html ng-app>
   <head>
         <title>Address Book</title>
   </head>
   <body ng-controller="PeopleController">
   <h1>Address Book</h1>	
   <div> 
         <div ng-repeat="person in people">
                <div>{{person.name}} - {{person.phone}}</div>
                <span>{{person.city}} </span>

         </div>
   </div>	

   <script src= "angular.min.js" type="text/javascript"></script>
   <script src= "scripts.js" type="text/javascript"></script>
   </body>
</html>

Tip

It is always a good practice to load your JS files at the end of the page just above the body tag and not in the head. You can read more about why this matters here at https://developer.yahoo.com/performance/rules.html.

As you can see here, we are defining the HTML5 doctype in the first line, and then we initialize the AngularJS application by using the ng-app directive. You'll also notice that we are using the ng-controller directive and assigning PeopleController to it. By doing so, we are defining the section of the DOM that is now within the scope of this controller.

You'll also notice a new directive called ng-repeat; this is the built-in directive used to display a list of items from a collection. The ng-repeat directive would simply duplicate the DOM element and bind the defined properties of the data object.

As you can see, ng-repeat makes it so easy and clean to display record sets as compared to doing this in jQuery or plain vanilla JavaScript.

Now, run your index.html in the browser and you should be seeing the names with their phone numbers and cities being displayed. The data from our model is showing up, which is good. Let us also inspect the code to have a look at the changes AngularJS is making to our markup.

All modern browsers allow you to inspect the source. And in most cases you can simply right-click on the page and select Inspect Element. In case you are not comfortable with Inspect, you can also do View Source. Refer to the following screenshot:

Tip

By the way, here I'm using Firebug, an awesome add-on for Mozilla Firefox.

As you look through the code, you'll notice that AngularJS is making a fair bit of change to the markup.

The first thing you'll notice is that AngularJS adds a class called ng-scope to every DOM element where the scope is initialized (we will get to what a scope is, in just a bit). It duplicates the entire DOM present within the ng-repeat directive. It is also adding a class called ng-binding to every element where the data is bound.

AngularJS will add different CSS classes depending on the directive being used. These can come in handy when you want to style, for example, the validation messages while working with forms. We'll see more about this in the chapters ahead.

Understanding the scope in AngularJS

Let us now look at this thing called the scope. As you might have noticed, we defined our people controller with a $scope parameter. We also had to define our people model as a part of this scope. While inspecting the elements, we also noticed multiple ng-scope classes being defined. So, what exactly is this scope and is it really that important?

As per AngularJS's documents, the scope object refers to the application model and provides an execution context for the expressions in the views.

The expression {{person.name}} is able to display the content only because the name is a property that can be accessed by the scope.

Another important thing to note is that every AngularJS app will have a root scope created at the ng-app directive. Many other directives could also create their own scope. Scopes are arranged in a hierarchical fashion following the DOM structure of the page. Child Scopes prototypically inherit from their parent scope.

The exception to this is in cases where a directive uses a scope option, it creates an isolated scope. More information about the directives and isolated scope is available in Chapter 5, Facebook Friends' Birthday Reminder App.

We'll get a better understanding of it as we see other examples.

 

Styling the app


Now, let us style the application to make it look a little better. We'll go back to our index.html and add a few CSS classes as follows:

<!DOCTYPE html>
<html ng-app>
   <head>
         <title>Address Book</title>
<link rel="stylesheet" type="text/css" href="styles.css">
   </head>
   <body ng-controller="PeopleController">
      <h1>Address Book</h1>	
   <div class="wrapper"
          <div class="contact-item" ng-repeat="person in people">
                <div class="name">{{person.name}} - {{person.phone}}</div>
                <div class="city">{{person.city}} </div>

          </div>
   </div>	

   <script src= "angular.min.js" type="text/javascript"></script>
   <script src= "scripts.js" type="text/javascript"></script>
   </body>
</html>

Now let's create our styles.css with the following CSS styling:

body{
   font-family: sans-serif;
   font-weight: 100;
   background:#ccc;
}
h1{
   text-align: center;
   color:#666;
   text-shadow:0px 2px 0px #fff;

}

.name{
   font-size:18px; 
}

.city{
   font-style: italic;
   font-size: 13px;
}

.wrapper{
   width:550px;
   margin: 0 auto;
   box-shadow:5px 5px 5px #555;
   background: #fff;
   border-radius: 15px;
   padding: 10px;

}
.contact-item{
   border-bottom: thin solid #ccc; 
   padding:10px;
}

As you can see from the CSS styles, we first style the body to give it a light gray background color using the #ccc (#ccc is the short code for #cccccc) hex code.

The H1 heading tag is styled to align center, with a dark gray text color and a text shadow. The styling for .name and .city is straightforward. Now, let us look at the styles for .wrapper using the following code:

.wrapper{
   width:650px;
   margin: 0 auto;
   box-shadow:5px 5px 5px #555;
   background: #fff;
   border-radius: 15px;
   padding: 10px;

}

Here, we are setting width of the div to 650px. The margin with 0 auto is used to place the div to the center of the screen irrespective of the screen resolution.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Now to make it look a little better, we'll give it a box-shadow and border radius. The following diagram explains what the options of the border radius mean:

For the .contact-item list, we give a border-bottom and some padding so that things stay a little spaced out.

With all this CSS in place, your app should be looking like this:

Sorting the contacts alphabetically

This looks nice, but it would be a good idea to have the names sorted alphabetically. For this, we will use AngularJS's built-in filter called orderBy.

In AngularJS, filters are used to format the data. One can use AngularJS's predefined filters or create your own. We'll learn more about filters later in this book.

All we need to do is modify the following section of the index.html as follows:

<div class="contact-item" ng-repeat="person in people| orderBy:'name'">
<div class="name">{{person.name}} - {{person.phone}}</div>
<span class="city">{{person.city}} </span>
</div>

Refresh your Index.html in the browser and you should notice the names are now sorted alphabetically.

 

Adding contacts to the Address Book


Now that we have our Address Book displaying our contacts nicely, let's now create a form to add contacts.

Let us add the markup for the Add a Contact form in the index.html file within the body tag as follows:

<div class="wrapper">
   <h2>Add a Contact</h2>
   Name: <input type="text" ng-model="newPerson.name"></input> 
   Phone: <input type="text" ng-model="newPerson.phone"></input>
   City: <input type="text" ng-model="newPerson.city"></input>
         <button ng-click="Save()">Save</button>
   </div>	

The preceding code is rather straightforward. We create a new div and reuse the wrapper class to style it.

We are adding the three textboxes for the name, phone, and city attributes. We bind these three textboxes to a model object called newPerson as follows:

  • ng-model='newPerson.name'

  • ng-model='newPerson.phone'

  • ng-model='newPerson.city'

We are also adding a button called Save and using the ng-click directive that will call the Save() function when the button is clicked.

Now, let us look at the JavaScript code that we will be writing in our scripts.js file:

$scope.Save=function(){
$scope.people.push({name:$scope.newPerson.name, phone:$scope.newPerson.phone, city:$scope.newPerson.city});
}

Tip

Since the Save() function is accessing the scope within the PeopleController function, it is imperative that the Save() function is written within the PeopleController function in the scripts.js file.

In the $scope.Save function, we simply capture the values from the input boxes and push this into our main people model.

Let us now refresh our index.html and try it out. Fill up the form and save it and you will immediately see it get added to the Address Book. This happens thanks to one of the many cool features of AngularJS called two-way data binding.

The ng-show and ng-hide directives

While the app is good as it is, maybe it's a good idea to have a button called Add Contact and display the Add Contact form only when that button is clicked.

Let us make use of AngularJS's ng-show and ng-hide directives to control the visibility of our Add Contact form.

The way they work is very straightforward. If the attribute ng-show='true', then the div is visible and vice versa. A point to note is that ng-show and ng-hide merely control the visibility of the DOM element.

Let's add our button called Add Contact and set up the ng-show and ng-hide directives such that when you click on Add Contact, the form shows up and at the same time this button disappears. And when the Save button is clicked, the form is hidden and the Add Contact button shows up again.

Let's modify our index.html as follows:

<center><button ng-click="ShowForm()" ng-hide="formVisibility "> Add Contact</button></center>
   <div ng-show="formVisibility " class="wrapper">
          <h2>Add a Contact</h2>
   Name: <input type="text" ng-model="newPerson.name"></input>
   Phone: <input type="text" ng-model="newPerson.phone"></input>
   City: <input type="text" ng-model="newPerson.city"></input>
         <button ng-click="Save()">Save</button>
   </div>	

We set the button to ng-hide='formVisibility' because when the value of formVisibility becomes true, it will hide the button. Similarly, ng-show= formVisibility will make the Add Contact form display when the value of formVisibility is true.

Now, let's add the piece of JavaScript to set the formVisibility values. Add the following code to your scripts.js file as follows:

$scope.ShowForm=function(){
$scope.formVisibility=true;
}

Tip

Make sure this new function is written within the main PeopleController function.

We will also add one line in our existing $scope.Save function to set the value of formVisibility to false.

Please update the $scope.Save() function as highlighted in the following code:

$scope.Save = function() {

    $scope.people.push({
        name: $scope.newPerson.name,
        phone: $scope.newPerson.phone,
        city: $scope.newPerson.city
    });
    $scope.formVisibility = false;

}

Reload your index.html and see the buttons in action.

Oh and just because we don't like the way those default buttons look, lets add a little bit of style to it.

Add the following CSS classes to your styles.css file:

button
{
   background:#080;
   color:#fff;
   padding:5px 15px;
   border-radius: 5px;
   border: thin solid #060;
"margin: 5px auto;"
}
button:hover{
   background: #0A0;
}

What we are simply doing here is setting a dark green color background for the button, giving the text a white color, and giving it some padding five pixels from the top- and bottom-side and 15 pixels from the left-hand side and right-hand side and adding some border radius.

The button:hover is a light green background color just to show the highlight when the user hovers the cursor over the button.

Reload your index.html page and we have our very first working and reasonably good-looking Address Book Application.

 

Summary


This concludes our first chapter. To quickly summarize, we went about building our Address Book App and in doing so learned about the various AngularJS directives such as ng-app and ng-repeat. We saw how two-way data bindings and expressions work and the importance of scope. We also saw how we can hide and show certain elements using the ng-show and ng-hide directives. Last but not least, we used some simple and easy CSS3 features to style our app.

In the next chapter, we will see the various tools that frontend developers should ideally have in their toolbox and how to go about using them.

About the Author

  • Vinci Rufus

    Vinci Rufus has been working with frontend technologies for close to 14 years now. He started his career by building games with Flash ActionScript and later moved to JavaScript and HTML5. During his spare time, he enjoys conducting workshops and training people.

    For a living, he mentors, guides, and helps build technology teams at Razorfish Neev, primarily in the area of commerce, usability, and emerging technologies.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Support Team, I have attached the below files while performing the transaction. 2016june23 at 3.00pm IST (Axis Bank CC).png 2016june23 at 3.22pm IST (Hsbc Transaction).png 2016june23 at 3.35pm IST (Hsbc Address change + transaction cancelled).png 2016june23 at 3.40pm IST (Standard Chartered Credit Card Transaction).png 2016june23 at 3.51pm IST (Standard Chartered Credit Card Transaction).png Spring Boot and Spring persistance.png I did transaction with (Axis bank at 3.00pm IST), (Hsbc bank at 3.22pm IST & 3.35pm IST), (Standard chartered bank at 3.40pm IST & 3.51pmIST), I took the screen shot of the same. All the transaction is showing billing address issue. When i try to crosscheck with Hsbc, Standard chartered, Axis bank (all the customer care person is telling that they does not received any notificaiton for hitting their site for transaction), they are asking to check with your site. But packtpub is not giving proper response
udmærket video er ikke færdih med den endnu
More than blueprints it work into a long example. Covers the basic part of developing a blueprint.
AngularJS Web Application Development Blueprints
Unlock this book and the full library for FREE
Start free trial