Vous êtes sur la page 1sur 11

Introduction to Angular.

js
Rahul Rajat Singh, 5 Jul 2015

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.

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

Hide Copy Code


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

Hide Copy Code

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

Hide Copy Code

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

Hide Copy Code


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

Hide Copy Code


<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. Let's see how this can be done.

Hide Copy Code

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

Hide Copy Code


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

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

Vous aimerez peut-être aussi