Click here to Skip to main content
15,867,704 members
Articles / Web Development / HTML

Angular Tutorial - Part 1: Introduction to Angular.js

Rate me:
Please Sign up or sign in to vote.
4.90/5 (89 votes)
5 Jul 2015CPOL15 min read 102.6K   1.8K   171   20
Basics of Angular.Js

Introduction

In this article, we will look at the basics of Angular.Js. This is the first part of an article series. The main objective of this series is to learn about Angular and see how Angular helps us in developing more flexible, maintainable and testable client side web applications and that too, without compromising the productivity.

Link to complete series:

  1. Angular Tutorial - Part 1: Introduction to Angular.js
  2. Angular Tutorial - Part 2: Understanding Modules and Controllers
  3. Angular Tutorial - Part 3: Understanding and using Directives
  4. Angular Tutorial - Part 4: Understanding and Implementing Filters
  5. Angular Tutorial - Part 5: Understanding and Implementing Services
  6. Angular Tutorial - Part 6: Building and Validating Data Entry Forms
  7. Angular Tutorial - Part 7: Understanding Single Page Applications and Angular Routing

Background

If we take a look back in time and see how our software applications have evolved, then we can clearly see how the application development and development model have evolved. Almost two decades ago, most software applications were getting built as standalone applications. These applications were targeted at a single user and ran on their operating systems.

Then came the need to share data across multiple users and a need to store data at a central location. This need gave birth to distributed applications. Distributed applications ran as standalone applications on the user’s machine giving him a rich user interface (let's call it desktop like experience) to work with, and behind the scenes, these applications sent data to a server.

When world wide web Web started gaining momentum, we saw a rise of web applications. Web applications, when compared to distributed applications, were sandboxed in a web browser and HTML and HTTP were used to let the user perform operations on the data which is stored on the remote server.

Back then, the major differentiating factor for these two applications was that the distributed applications provided an interactive user experience whereas web applications provided very limited features (due to technology limitations). The downside of distributed applications was that it was very difficult to distribute. Also, ensuring that each application update has reached across all users was a nightmare. Web applications had no such problems because once the application is updated on the server, all users got the updated applications.

Both these approaches had pros and cons and something needed to be done to get the best of both worlds. This is where browser plugin based applications like Flash applications and Silverlight applications came into the picture. These technologies filled in the gap for all the functionality not possible with HTML. They provided the possibility of creating rich internet applications that ran in the browser. The only downside of this was that the user needed to install the browser plug-in to get these applications to work.

Then came the time when browsers became more capable and HTML became more mature. Creating a rich internet application became possible only using browser based client side technologies. This led developers to write client side code using HTML and JavaScript to create rich internet applications. No need for plugins like Flash and Silverlight.

But since HTML and JavaScript were never meant to be used for writing full fledged web applications, these applications had all the HTML and JavaScript code intermingled. This led to spaghetti code and these client side HTML/JavaScript applications (Single Page Applications or SPAs) became a maintenance nightmare. Also creating such application using vanilla JavaScript and HTML was a big problem from the productivity perspective.

So why should we write JavaScript/HTML based apps when they lead to bad code? The main reason for wanting to create a single page application is that they allow us to create a more native-like/desktop-like/device-like application experience to the user. Also, it has few other benefits like all the client side processing logic can easily be pushed to the users' browser thereby saving some precious server resources. With the advent of CDNs, it became quite easy to deliver such applications to the client with minimum latency and thereby increase both performance and usability experience.

So the need of the hour was to be able to create JavaScript based web apps in a structured manner and this created a need for JavaScript frameworks and libraries that provided some structure to the JavaScript apps. Currently, there are quite a few Open Source JavaScript frameworks available that help us solve the problem of spaghetti code. These frameworks let us design our applications in a structured manner. AngularJS is also one of these new generation libraries and frameworks that let us write more flexible, maintainable and testable client side web applications and that too without compromising the productivity.

A Note on Single Page Applications

I have used a term Single Page Applications above but it might be worth talking about it in little details as some of the developers working with traditional web development model may find it misleading. From a web application perspective, what is a page? If we want to develop a static website, we will create a set of HTML pages linked to each other. Whenever a user navigates from one page to another, a request for the new page is sent to the server and the new requested HTML page is sent back to the client.

When we look the same concept from the server side technology perspective like ASP.NET web forms and PHP, we still find that these frameworks have a notion of pages, i.e., .ASPX, .PHP. Whenever user requests for a page, the server generates an HTML from these server pages and sends back the response HTML to the browser. Also, if we consider the MVC web frameworks like ASP.NET MVC and Ruby on Rails, these frameworks don't have a concept of physical pages but rather they invoke an action whenever a user requests for a page and then sends back the appropriate response HTML to the browser. But from the browser perspective, it is getting a new HTML page sent back to it.

So all these technologies can be said to contain multiple pages or multiple page web applications. These applications make a postback to the server on each user request and get back a new HTML page for the user. Now if we try to understand what a single page application is, it can simply be defined as an application that will load a single HTML page in the browser and on each subsequent request, the new data and new HTML is pulled from the server using AJAX. This is to give the user an impression that only a single page is loaded in the browser and the needed app areas are getting refreshed/reloaded on his requests.

Now the big question, when should we create a single page application? I read a very nice tweet from someone few days ago and that goes something like this "Single Page Application is a Myth. It is ok to have multiple pages in our application but not more than needed". What it means is that whether to have a complete single page application or to have multi page applications with a lot of mini single page applications in a single page or to have a complete multiple page application, it all depends on the application requirements and usability needs. Creating a Single Page Applications(SPA) just because everyone is creating it might not be a good idea. It should be created when an application demands it. One example could be that we want to have an app that will be used as web app and will also be packed as a device app. Then it makes perfect sense to have the complete application designed as a SPA.

Which brings us to the last and perhaps the most important question. Should we care about Angular if we are not working on a SPA? This question is in the mind of many developers working on web frameworks like ASP.NET MVC and/or Ruby on Rails who are using jquery to perform all the AJAX operations. There is no right or wrong answer for this question, but in my opinion it is still better to use Angular. Few reasons for that could be that firstly Angular provides as application framework that jquery is lacking. Application framework will let you manage separate DOM elements in a much better manner than vanilla jquery. Also, when using Angular, the code could be structured in a much better way that simple jquery and JavaScript code scattered across. Perhaps it's too early to visualize the benefits but I am hoping that once the developers get to know Angular better, they will be able to make a better decision so maybe we should revisit this question at the end of the series too.

Note: Using Angular does not mean that we cannot use jquery along with it. In fact, Angular also uses a lite version of jQuery internally(JQLite). If we want to use jquery, then just by including the jquery before Angular file, we can actually let Angular know that it can use full version of jquery instead of inbuilt jqlite. Angular and jQuery work in unison and can be a very powerful combination in most cases.

Separation of Concerns and MVC

One of the best things about a good application architecture is the Separation of Concerns (SoC). The best part of the Angular.Js framework is the ability to provide this separation of concerns using the MVC pattern. In Angular, the view is the plain old HTML DOM, the controllers are JavaScript classes, and the model data is stored in JavaScript object's properties. Models are mainly to represent the business objects. These business objects are used by the views so that the user can act upon them, i.e., perform CRUD operations. The controller is the one that provides the mechanism for interaction between models and views.

Image 1

The above image represent a strict MVC pattern but Angular is not really a strict MVC pattern. It is more apt to say that Angular fits in MV* pattern. Some might even say that the Angular controller is really a view model and Angular is more of a MVVM. But let's leave that discussion for now because most of it also depends on how we are using it. Perhaps at this moment, it would suffice to say that Angular does provide a great separation of concerns and it is flexible enough to let us take the architectural approach we want to take.

Note: If you don't know about MVC, MV* and MVVM (perhaps for beginners, these terms can be daunting), don't sweat over it too much. Things will get much clearer as we proceed.

What is Angular.Js

Angular.js is a lightweight framework that lets us create JavaScript Applications (and SPAs) in a structured manner. It is based on the Model-View-Whatever (MV*) pattern. It is best suited for creating applications using a HTTP based services for persisting and retrieving data (perhaps RESTful services).

At the minimum, an Angular application mainly contains views, controllers and models. The views are plain HTML that take care of showing the data to the user and acting upon user interactions. Behind the view, there is a controller which takes care of all the core business logic and perhaps all the communication with the server (which ideally should never be done as an Angular service is the right place to do this). The communication between the controller and the view is being done by using a shared object called scope. Scope can be thought of as being located between controller and view as a bridge which is used to exchange information between controller and view.

But for larger application with much more complexity, we might need to refactor our code and try to move the logic from controller to other components such as services. We will learn more about services later but for now, it's important to know that we can create services in Angular to put the reusable chunk of functionalities which can be used from multiple controllers and views. It is also a good idea to just be aware of other Angular components like filters and directives. Filters can be used to filter and/or process the data before showing it on the view. Directives is a mechanism that let the developers extend the HTML vocabulary and define custom tags and attributes.

Getting to Know the Players

We will look at the all the Angular components like controllers, services, filters and directives in details in later articles, but let's just briefly look at the components Angular provides and what is the role of each component.

  • Views: Plain HTML documents containing Angular specific tags and markup along with HTML.
  • Controllers: A controller is a simple JavaScript class that contains all the business logic implementation to be used by the view.
  • Models: Plain old JavaScript Object that contain data to represent business entities.
  • Services: Classes containing reusable pieces of code/functionality.
  • Filters: Filter and/or process the data.
  • Directives: Directives is a mechanism that let the developers extend the HTML vocabulary and define custom HTML like tags and attributes.

Note: One important thing to note while reading these above definitions is that they are meant to get the reader acquainted with the basic components. The actual definition of these components is much more elaborate and there are some best practices and standards associated with these components usage. I have intentionally kept these definitions simple just to avoid confusion. We will look at the detailed definitions and best practices in the later articles.

The Infamous Hello World

No Introductory article is complete without the infamous "Hello World" example. As for the Angular version, what we will do here is that I will create a simple controller and initialize the "Hello World" message in the controller scope. We will then see how we can use Angular two way biding to easily propagate the changes in this message from view to controller and then from controller to view again.

Note: I will be putting all the code for this simple app in a single HTML file which again is not recommended but is being done just to demonstrate the concepts.

Let us start by creating a simple HTML page that will contain a heading to show our message and a textbox to update this message.

HTML
<html>
	<head>

	</head>

	<body>
		<h2>Message will come here</h2>		
		<input type="text" />
	</body>
</html>

Now let us include the Angular.Js and let the HTML page know that we want to use Angular with this page. This can be done by using the ng-app directive. Usually, this is done at the html tag so that the complete page can be accessed by Angular. If we do this on any other tag, only the HTML nested inside that element will be accessible by Angular. Let's define the ng-app called "sample" for this view.

HTML
<html ng-app="sample">
	<head>		
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" 
                type="text/JavaScript"></script>
	</head>

	<body>
		<h2>Message will come here</h2>		
		<input type="text" />
	</body>
</html>

The next thing we need to do is to create an Angular module with the same name as the np-app, i.e., "sample". The module is like an application definition. It contains all the different parts of the Angular application. All the controllers, services and directives should belong to a module. So let's define a module "sample" for our application.

HTML
<html ng-app="sample">
	<head>		
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"
                 type="text/JavaScript"></script>
		
		<script type="text/JavaScript">
		var sample = angular.module("sample", []);
		</script>	
		
	</head>

	<body>
		<h2>Message will come here</h2>		
		<input type="text" />
	</body>
</html>

Now we will define a controller that will initialize a message property on scope object. Let's see how we can define this controller.

HTML
<html ng-app="sample">
	<head>		
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" 
                 type="text/JavaScript"></script>
		
		<script type="text/JavaScript">
		var sample = angular.module("sample", []);
		
		
		sample.controller("sampleCtrl", ["$scope", function ($scope) {
			$scope.message = "Hello World";
		}]);
		</script>	
		
	</head>

	<body>
		<h2>Message will come here</h2>		
		<input type="text" />
	</body>
</html>

Next we need to configure the HTML heading to show the message. This can be done by using the ng-controller directive on the HTML tag that wants to use the controller. We will do it with the body tag. Also to let the heading tag know about which message to show, we need to use the ng-bind attribute with the heading as:

HTML
<html ng-app="sample">
	<head>		
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"
                 type="text/JavaScript"></script>
		
		<script type="text/JavaScript">
		var sample = angular.module("sample", []);
		
		
		sample.controller("sampleCtrl", ["$scope", function ($scope) {
			$scope.message = "Hello World";
		}]);
		</script>	
		
	</head>

	<body ng-controller="sampleCtrl">
		<h2 ng-bind="message"></h2>		
		<input type="text" />
	</body>
</html>

Now if we run the application and see the heading, we can see the message defined in our controller appearing on our heading.

Image 2

Next, we want to associate the textbox with the message in such a way that the value entered in the textbox will get assigned to the $scope.message in the controller. To show the message, we used ng-bind which essentially means controller to view binding. To facilitate passing of data from view to controller, we need to use ng-model which will be a two way binding between view and controller. Let's see how this can be done.

HTML
<html ng-app="sample">
	<head>		
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"
                 type="text/JavaScript"></script>
		
		<script type="text/JavaScript">
		var sample = angular.module("sample", []);
		
		
		sample.controller("sampleCtrl", ["$scope", function ($scope) {
			$scope.message = "Hello World";
		}]);
		</script>	
		
	</head>

	<body ng-controller="sampleCtrl">
		<h2 ng-bind="message"></h2>		
		<input type="text" ng-model="message"/>
	</body>
</html>

Now if we run the application and enter some value in the textbox, we can see that value being passed to $scope.message and in turn appearing on the heading.

Image 3

One more interesting thing to talk about here could be Angular expressions. Anything written between double curly braces are treated as Angular expressions. So if we write something like {{ 2 + 2 }},  Angular will evaluate it and print the result as 4. If we use expressions on scope properties, it will be equivalent to ng-bind. Let's add one more heading and try to use expression to show the message to the user.

HTML
<html ng-app="sample">
	<head>		
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"
                 type="text/JavaScript"></script>
		
		<script type="text/JavaScript">
		var sample = angular.module("sample", []);
		
		
		sample.controller("sampleCtrl", ["$scope", function ($scope) {
			$scope.message = "Hello World";
		}]);
		</script>	
		
	</head>

	<body ng-controller="sampleCtrl">
		<h2 ng-bind="message"></h2>		
		<h2>{{message}}</h2>		
		<input type="text" ng-model="message"/>
	</body>
</html>

And the result for the new heading will be same as the heading that contains ng-bind.

Image 4

Organizing the Code

When we are working on a project that is very large, it is important to organize our project in a proper structure. There are two main ways of organizing the projects. One is known as the specific style where we group the code based on the type of components, so the code structure will look like the following:

Image 5

Another approach is called domain style where we group the code based on the logical domain entities and then put all the components inside the respective domain folders. The following image shows how this can be done.

Image 6

Either way, choosing the structuring style will mainly depend on the standards being following by the organization.

Point of Interest

In this article, we looked at the basic concepts behind angular.js. I think it is fair to say that we have not even started. We did look at a simple example and saw how we can create modules, controllers and use directives like ng-bind and ng-modal. How we can use expressions but this article mainly said this needs to be done and we never looked at why we are doing things in a certain way. In later articles, we will dive deeper into each component and see why we are doing what we are doing and how we can use Angular to create awesome web apps. Let's look at the details of Angular modules and controllers in the next article.

History

  • 20th May, 2015: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralMinor typo in otherwise very good article Pin
charles9221-Feb-18 6:55
charles9221-Feb-18 6:55 
PraiseReally nice introduction Pin
SkinnyGlass12-Oct-16 23:43
professionalSkinnyGlass12-Oct-16 23:43 
PraiseNice introduction. Pin
Amit Gupta AG17-Aug-16 4:07
Amit Gupta AG17-Aug-16 4:07 
GeneralMy vote of 5 Pin
Tridip Bhattacharjee2-Jun-16 21:43
professionalTridip Bhattacharjee2-Jun-16 21:43 
QuestionOne request for custom directives in details Pin
Tridip Bhattacharjee2-Jun-16 21:43
professionalTridip Bhattacharjee2-Jun-16 21:43 
QuestionGrate works Pin
Raviteja Swayampu10-May-16 0:29
Raviteja Swayampu10-May-16 0:29 
GeneralMy vote of 5 Pin
MarcusCole683324-Mar-16 4:50
professionalMarcusCole683324-Mar-16 4:50 
GeneralMy vote of 5 Pin
D V L17-Mar-16 8:21
professionalD V L17-Mar-16 8:21 
GeneralMy vote of 5 Pin
Jhonathan Izquierdo15-Dec-15 3:29
Jhonathan Izquierdo15-Dec-15 3:29 
Questiongreat job Pin
Norbert@Germany10-Nov-15 1:40
professionalNorbert@Germany10-Nov-15 1:40 
GeneralVery Good Pin
Paulo Augusto Kunzel9-Sep-15 4:12
professionalPaulo Augusto Kunzel9-Sep-15 4:12 
QuestionMy Vote 5 Pin
Dharmesh .S. Patil27-Aug-15 20:42
professionalDharmesh .S. Patil27-Aug-15 20:42 
GeneralMy vote of 5 Pin
Sadequzzaman Monoj21-Jul-15 23:08
professionalSadequzzaman Monoj21-Jul-15 23:08 
GeneralParts 5 and up Pin
Tomas Keri9-Jul-15 10:02
Tomas Keri9-Jul-15 10:02 
GeneralRe: Parts 5 and up Pin
Rahul Rajat Singh9-Jul-15 17:38
professionalRahul Rajat Singh9-Jul-15 17:38 
only one reason - they are still in my head Smile | :) .

I mean I am yet to write them. Hopefully I will be able to put them all here in this month only.

GeneralRe: Parts 5 and up Pin
Tomas Keri10-Jul-15 3:57
Tomas Keri10-Jul-15 3:57 
GeneralMy vote of 5 Pin
Pratik Bhuva15-Jun-15 23:12
professionalPratik Bhuva15-Jun-15 23:12 
QuestionExcellent Article Pin
Santhakumar Munuswamy @ Chennai22-May-15 22:15
professionalSanthakumar Munuswamy @ Chennai22-May-15 22:15 
GeneralMy vote of 5 Pin
Carlos190721-May-15 0:36
professionalCarlos190721-May-15 0:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.