In the previous article we had a look at MEAN - the new technology stack in web development. MEAN proposes a different approach on all layers: client-side, server-side, database and operating system/platform. In this article, we will have a more detail look on one of the technologies from the stack, AngularJS, which is targeting client-side layer.

The traditional way of developing web applications is based on the following idiom: 

  1. the user initiate a request from the browser; 
  2. the request is received on the server-side and dispatched to the appropriate components to process it;
  3. the server-side components perform the action(s) associated with the request, gather the data, create the response HTML page and send the response back to the client;
  4. very little processing is done on the client-side, in the browser; everything, both data and the presentation is delivered dynamically, by the server.

This was fine back in the old days when client machines were not powerful, and they were exempt from all the "heavy-lifting": just get the HTML page as response and render it. The web application, in this case, was actually a set of pages, laying on the server-side, and served to the client based on the requests received (enhanced with dynamic data and formatted if it was the
case). 

AngularJS is a MVC (Model-View-Controller) web development framework, developed in JavaScript and used to build Single Page Applications - SPA. This is the exact opposite of the traditional web applications. A SPA is, like the name suggests, a single page in which content is swapped based on the current context (or better said state) of execution and on the client actions. The main characteristics of a SPA are:

  1. is single page, obviously; 
  2. is client side;
  3. is component-oriented;
  4. is asynchronous/event-driven.

An SPA is client-side in the sense that most of the processing associated with a request is done in the browser. AngularJS allows you to handle data validation, application logic and navigation between "pages" (or better called states) and rely on the server only to get/send raw data. That is it. Since we are dealing with SPA, we not actually navigating from one page to another, we show/hide content inside the same page (content is residing inside <div> elements) based on the navigation logic.

Traditional web development is page-centric, because the complete page must be created before it is send back to the client. Opposite to this, SPA is component-oriented: pieces of the page are represented as components, which encapsulate both data and behaviour and communicate between them using events. The content displayed or hidden inside the page is managed by components. Through components, navigation takes place, server-side components are called, events are raised and handled. And that makes SPA also event-driven.

Finally, because an SPA goes to the server only to get data and partially refresh itself in order to display that data, there is no synchronous request; a synchronous request is by definition page-oriented. By using promises, which is a very common feature implemented in JavaScript, you make a call to the server and when the data is received, you can then act upon it (do business logic, format it and display it). 

All the features described above are SPA-related. AngularJS implements them but is not the only one: Backbone, Ember, Knockout are just a few other frameworks that can help building SPA applications and also implement these features. What is then specific to Angular?

AngularJS is HTML-Centric

HTML language is great for static documents, but how we can manage dynamic content with it? In the traditional way, everything is generated on the server and pushed to the client. AngularJS allows you to extend HTML vocabulary with custom elements and attributes, specific to your application, which will add dynamic character to the content displayed, and makes the complete HTML very expressive, easier to read and quick to develop. This is opposite to others approaches taken by JavaScript frameworks, that is manipulating directly the DOM.

This is achieved through directives. Directives are JavaScript components used directly into the HTML page as elements or attributes, enhancing the page functionality. The main role of Angular is that of a preprocessor, which preprocess the HTML page before it is delivered to the browser to be rendered. During the preprocessing, all directives are evaluated and transformed into combinations of well-known HTML tags that a browser knows how to display.

Under the hood, directives can use partial HTML fragments as template files based on which, during preprocessing, and applying the directive logic, the final HTML code is generated. For example have a look on the following snippet: 

<div ng-controller="MyController">
     <customer-summary></customer-summary>
</div>

There is no ng-controller attribute for HTML div element defined in the standard. This is an Angular directive, defined as attribute, which tells Angular that whatever is contained inside the <div> is managed by MyController controller object. This is an Angular scope. So, whatever is defined in the controller (like variable, functions) can be used only in that scope.

And what about customer-summary element? Clearly not a part of HTML standard also. Is just another custom directive that may display a panel with the most important information about a customer, something that is specific to your application and you wrote it order to encapsulate and reuse this behavior (that is another example of component-orientation for AngularJS).. It is easier to read this code, and the developer will immediately understand what is the expected output, as opposite to looking at some JavaScript code that manipulates the DOM to define the elements for showing the customer summary.

AngularJS is Declarative

Declarative programming means: This is what I would like to happens as oppose to imperative way which means: This is how you should do it. The difference is in the mindset. Using directives and other constructs, AngularJS helps you focusing on what you want to produce as output, and not on how to manipulate HTML elements in order to construct the output. Let's look at the following example, which simply prints the name you enter in the text field, down in the H1 heading below:

<html>
<head>
<title>Hello World App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>

This is a complete AngularJS application. And there is not a single line of code that needed to be written. You know you want to display the name entered in the input field, down in the heading below it, so you use AngularJS to represent what you want to happen. You didn't care about what JavaScript code is executed behind in order to get the value from the input field and put it in the H1 tag.


Now let's look at the jQuery version of it:

<html ng-app>
<head>
<title>Hello World jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
'use strict';
$(document).ready(function () {
var input = $("#yourName");
input.on('keyup', function () {
$('#yourNameGoesHere').html(input.val());
});
});
</script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" id="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello <span id="yourNameGoesHere"></span>!</h1>
</div>
</body>

Although the example is trivial, in the imperative approach you need to write some code. You need to grab the input field, to associate with it an event and on the response for that event, grab another HTML element where you want to put the text, and set the value of the input field. Just by looking at the HTML code is not obvious what is happening. You need to check the JavaScript, see what is going on there, check the HTML elements affected, etc. Is not very expressive and as readable as the Angular version. And where is code there should be also unit tests. In the Angular version there is no code, so there is no unit test to write. In jQuery, as simple as it seems, you still need to have some unit tests, to validate the behavior. 

AngularJS has Dependency-injection

Angular is handling for you any dependencies that one component might have on others by creating and injecting them, so that they are already available for the component code to work with. Besides dumping the boilerplate code of creating instances of components manually and then using them, what you get is something more important: your code becomes much more easier to test. For example, if you want to unit test a component that makes HTTP requests, but you don't want to do them for real, you inject a mock component  ($httpBackend in this case)  instead of the one that performs the actual HTTP requests(which is $http service), so you can specify different responses to the requests sent and check various scenarios in your unit tests. 

AngularJS was written by testers, so it was built to be very testable. Everything in it supports this idea: is declarative, is component-oriented with isolated scopes, has dependency injection. All these helps you encapsulate the behavior and make it easier to test.