Click here to Skip to main content
13,195,379 members (66,247 online)
Click here to Skip to main content
Add your own
alternative version

Stats

69.9K views
1.5K downloads
169 bookmarked
Posted 20 May 2015

Angular Tutorial - Part 1: Introduction to Angular.js

, 5 Jul 2015
Rate this:
Please Sign up or sign in to vote.
In this article we will look at the 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 with 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 has evolved. Almost two decade 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 (les 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 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 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 and 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 increasing 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 with the productivity.

A Note on Single Page Applications

I have used a term Single Page Applications above but it might be worth to talk 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 send 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 send back the appropriate response HTML to the browser. But from the browser perspective it is getting a new HTML page sent back to the 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 requests the new data and new HTML is pulled from the server using AJAX. This is 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 have read a very nice tweet from someone few days back 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 an 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 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 its 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. 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.

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 lets leave that discussion for now because most of it also depends on how we are using it. Perhaps at this moment it suffice to say that angular does provide a great separation of concern 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 clear 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 takes 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 its 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 lets 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 definition 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>
	<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. Lets define the ng-app called "sample" for this view.

<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 lets define a module "sample" for our application.

<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. Lets see how we can define this controller.

<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 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.

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. Lets see how this can be done.

<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.

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. Lets add one more heading and try to use expression to show the message to the user.

<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.

Organizing the Code

When we are working on a project that is a 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 following.

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. Following image shows how this can be done.

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. Lets look at the details of angular modules and controllers in the next article.

History

  • 20 May 2015: First version

License

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

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
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

You may also be interested in...

Comments and Discussions

 
PraiseReally nice introduction Pin
SkinnyGlass12-Oct-16 23:43
professionalSkinnyGlass12-Oct-16 23:43 
PraiseNice introduction. Pin
Amit Gupta AG17-Aug-16 4:07
memberAmit 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
memberRaviteja Swayampu10-May-16 0:29 
GeneralMy vote of 5 Pin
MarcusCole09207624-Mar-16 4:50
professionalMarcusCole09207624-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
memberJhonathan 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
memberTomas Keri9-Jul-15 10:02 
GeneralRe: Parts 5 and up Pin
Rahul Rajat Singh9-Jul-15 17:38
mvpRahul Rajat Singh9-Jul-15 17:38 
GeneralRe: Parts 5 and up Pin
Tomas Keri10-Jul-15 3:57
memberTomas 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171019.1 | Last Updated 6 Jul 2015
Article Copyright 2015 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid