Understanding AngularJS

- select the contributor at the end of the page -

This article is the first in a series about understanding AngularJS. The first two articles will provide an overview of AngularJS, how it fits into Web development, and the overall design of the library. After that, we’ll go deeper into the various aspects of development with AngularJS, including in-depth information about the architecture of the library.

Web development

In order to fully understand AngularJS, it’s important to first take a look at Web development and how it has evolved over the past two decades. During this time, we went from creating pages with markup and hyperlinks to building fully interactive and rich applications in the browser. Three primary tools exist as the basis of that Web development platform on the client including HTML, JavaScript and CSS. While these three components are still the cornerstone of Web development, many new frameworks and libraries have been built on top of them to simplify things (or to meet challenging requirements).

But let’s get back to the primary tools for a moment.

HTML, of course, provides the semantic markup of the content on a page. HTML 5 offers several new tags primarily focused on the semantic structure of a document including Article, Section and Footer, just to name a few. Over the years developers have moved away from HTML markup to provide visual or design structure, and now rely more on CSS to define these things. CSS not only defines visual attributes like font size, colors and visibility, but also the size and alignment of items on the page. As CSS evolved it added more advanced features like transforms, which add a level of interactivity through the declarative language. CSS is also a major component of making websites responsive so they can render on various devices and screen resolutions.

And then there’s JavaScript, which has enabled us to build applications in the browser. JavaScript allows us to take the semantic markup, along with the styles applied through CSS, and make them more dynamic in the browser, rather than using static resources that are downloaded once and applied. JavaScript lets us interact with the Document Object Model (DOM) to change the HTML tree or the data in the page. For example, a page can load data from the server using another HTTP request initiated through JavaScript and can then change the data in the page by adding to or replacing the existing HTML data. This makes pages more responsive and reduces full page reloads in the browser.

You can also use JavaScript to change the CSS styles applied to a particular object or set of objects on a page. This allows the page to respond to user input and change the layout or styles. For example, a large set of data may be presented with titles and detail but with a single detail visible at a time. As the user clicks on another title, the details for that title become visible while other details are hidden.

There’s no denying that the combination of HTML, CSS and JavaScript has enabled the construction of some amazing interfaces. However, advanced requirements in an application can result in the need for more advanced or complex JavaScript to be written. Additionally, because JavaScript is not a compiled language, reusing scripts often becomes an exercise in copy-and-paste development. For this and other reasons, developers created frameworks or libraries of encapsulated functionality to be used across applications. These libraries often ease the development of more complex interactions between the three core pillars of Web development.

Frameworks and libraries

Frameworks provide a set of constructs for building your application, while libraries are sets of useful functionality encapsulated in one or more JavaScript files – and there’s no shortage of either. jQuery, for one, is a popular library that you can use all over your application logic to manipulate the structure of the page or change the style and layout of items. AngularJS and Twitter Bootstrap are examples of frameworks used for building an application. When you choose a framework it typically drives some portion of the application design because certain things need to be in place for the framework to function properly.

Keeping up with all the new libraries is difficult and not necessary for everyone. As libraries and frameworks are introduced to the community, developers with a distinct need for that functionality will use and test the new solutions. After feedback cycles and several versions, the most viable solutions will rise to the top, be featured at conferences and on blogs, and become well known as trusted tools. The aforementioned jQuery, created by John Resig, is a great example of this. It started out as a lightweight library to simplify the modification of the DOM, which is the representation of the HTML structure of a Web page.

As developers struggled to build applications that worked across browsers using the various APIs available, Resig created jQuery as a way to simplify selecting DOM elements. He did this by using the same selector syntax found in CSS. Once selected, elements could easily be manipulated, have event handlers attached, or be removed completely from the document. As developers tested this in their applications and gave feedback, the library improved and is now a default option in many applications. In fact, many other libraries and frameworks now depend on jQuery rather than rewriting the functionality it provides.

Single Page Applications

As more applications were built with Web technologies, user demands increased. One common requirement today is that an application be responsive. This can either mean that it adapts to different screen sizes and resolutions or that it responds quickly to user input without reloading an entire page. The first is generally achieved with CSS and frameworks like Bootstrap that focus on CSS layouts which adjust based on the screen size. The second is achieved using a number of techniques to respond to user input and by manipulating the DOM to change just those portions of the page that need updating, while leaving those that don’t (like navigation elements and sidebars). Not surprisingly, there are challenges associated with this.

Take bookmarking, for example; if a user navigates to a page, then the content changes, adding a bookmark generally creates a pointer to the original content. This doesn’t exactly create an ideal user experience. Retrieving data from the server, while not incredibly challenging, requires use of the XmlHttpRequest object provided in modern Web browsers. The model used to retrieve data requires a series of callbacks and checking of status codes, as well as managing the parsing or processing of the response data to get it into a usable format.

Of course, you can overcome these challenges with diligent coding, encapsulation, and by using current Web standards. In order to have a consistent experience across your applications you could wrap this functionality up into a set of JavaScript files that can be included in your Web applications. However, once you’ve addressed all of these challenges, you’ve created your own framework rather than using an existing one!

This type of application (in which the content on the page is dynamically loaded) is commonly referred to as a Single Page Application (SPA) because the application logic and interaction happen on a single page, with new data and content loaded dynamically. There are now several application frameworks that attempt to simplify the process of building single page applications with features around routing, data binding, client-side templating and AJAX (Asynchronous JavaScript And XML) wrappers for data access -- and all of this, finally, brings us to AngularJS.

AngularJS

As a framework for building single page applications, AngularJS provides a set of functionality to greatly reduce the amount of code written and effort involved in making an application functional. It prescribes certain aspects of your application design as a trade-off for the features it provides. AngularJS is also described as a Model-View-Controller (MVC) framework or architecture because it takes a modular approach to building your applications. Each view is defined in HTML that has a JavaScript controller module and model that drive the interaction. Even better, AngularJS has been around long enough to have been tested in large applications and has gone through several revisions.

AngularJS is made up of one or more JavaScript files, depending on the functionality your application will leverage. Rather than one bloated JavaScript file added to all of your applications, there is a core file that includes the major framework features and additional files or modules you can add to layer additional functionality onto the core framework.  For example, there's a Resource module that provides a wrapper around a core HTTP service for interacting with RESTful APIs. You do not add the Javascript file for the resource module to your application if you are not using it.

AngularJS, and the various modules, can be added to an application by using a package manager like NPM, Bower or NuGet, to name a few. All package managers provide individual packages for the core and additional modules, and all applications require the installation of the core module with optional modules like Route or Resource added as needed.

Templates

When data is dynamically rendered in a page it's often fetched as a stream of JavaScript Object Notation (JSON) or XML. That data needs to be rendered in HTML to be presented in the browser. Rather than dynamically creating HTML markup in JavaScript by hand, templates let you define the markup with placeholders for the data to be presented. This is helpful and performs better  in simple cases, and more so in cases where repeating data will be presented with the same HTML markup and changes only in the data elements presented.

Templates can be defined in several ways, but it’s common to define each in its own HTML file deployed with the application. Each template file includes the HTML fragment that defines the template for the view. This enables the application views, despite being included in a single page, to be managed and considered separately. Another important aspect of templates is flexibility. AngularJS templates can include markup known as filters, which provide useful functionality such as formatting of currency, numbers, and date/time data, allowing the use of a single template across cultures and regions.

Data binding

Closely related to templates is the notion of binding data, in the form of JavaScript objects, to the HTML elements on the page. Binding can be used for display purposes when retrieving and showing data to the user. But AngularJS supports two-way binding, which means that input elements in HTML forms can also be bound to those JavaScript objects.

Having a data binding system means that application developers don’t have to manually write a lot of infrastructure code to read or set values on the HTML elements. This separation of concerns means that to change a value in the display, the code simply needs to update the JavaScript object and the changes will be reflected in the HTML interface. Likewise, when responding to a user-input event like a button click, the developer can retrieve the values directly from the JavaScript object instead of having to traverse the DOM to read the values from the HTML elements.

The data binding model in AngularJS is both simple and powerful. The majority of the binding model involves declarative statements in the HTML templates which enables AngularJS to keep the DOM elements and JavaScript objects synchronized. In some scenarios you may need to help AngularJS update, but most of the time it’s handled for you.

Routing

As mentioned previously, managing the URL of a resource (to enable navigation within a single page application, and support linking and bookmarking to different views) can be a challenge. The Routing module takes advantage of the HTML anchor and hyperlinking features to create unique URLs for the various views in your application. For example, the following two URLs point to the same page, but a different anchor in that page:

http://yourdomain/SinglePageApp#Customers

http://yourdomain/SinglePageApp#CustomerDetails

This means users can bookmark their place in the application and return to the specific view rather than the default view in your application. In addition, the routing module enables you to handle routing parameters such as an ID to identify a customer.

Promises

A big part of building responsive applications that work across networks is asynchronous programming. Asynchronous programing uses additional threads to process longer running work without stopping the updating of the user interface. Promises have become the de facto model for managing asynchronous work and AngularJS provides a promise model based on the popular Q library but focused on just the core features.  This service is used throughout AngularJS and provides a simplified interface for developers working with asynchronous operations in their Angular applications.

HTTP / AJAX

Accessing data over HTTP is a common requirement in single page applications. The XMLHttpRequest object can be used directly in JavaScript code, however, it’s commonly wrapped to reduce coding. In AngularJS the HTTP service wraps the XmlHttpRequest object to provide simple functions (such as get, post and put) that  use the promise model to provide asynchronous responses or errors. The AngularJS HTTP service also provides more advanced functionality enabling us to provide functions to transform and/or intercept the request or response to enable manipulating the configuration or content. This enables handling cross cutting concerns like error handling and authentication.

Resource

Following a common pattern of layering abstractions, AngularJS provides the Resource module which provides a typed interface over the HTTP service for RESTful Web APIs. Using this module allows you to focus on the resources in your RESTful API and extends objects with functions such as Query, Save and Delete. Like the HTTP service, the Resource service can be extended with custom methods and take advantage of transformations and interceptors.

Other features

The above list is a common set of features used in most applications, but AngularJS has other features and services as well. Additional modules, installed from their own JavaScript file and included separately, include support of animation, touch support on mobile devices, common UI messaging (errors and alerts e.g.) and working with cookies. These additional modules can be added as needed and each simplifies the related development process in your AngularJS application.

Unit Testing

AngularJS was conceived and built to be highly testable. It includes a mocking module and support for mocking things like the HTTP service in your unit tests. Because AngularJS leverages dependency injection heavily in the runtime, the various components can be more easily tested with mock implementations for any dependencies.

Takeaway

Now you have an overview of AngularJS and where it fits in the world of Web development and single page applications. You know that AngularJS provides a framework to simplify and speed the development of single page applications, addressing many common challenges. The next article in the series will examine the overall architecture of AngularJS applications and how the MVC model is used to build your application. After that, we’ll go more in depth with articles that dive into the various components of AngularJS applications such as controllers, models, views, services, filters and directives.

Get our content first. In your inbox.

Loading form...

If this message remains, it may be due to an ad blocker.

Contributor

Matt Milner

is an independent consultant specializing in Microsoft .NET application design and development. As a writer Matt has contributed to several journals and magazines including MSDN Magazine where he currently authors the workflow content for the Foundations column. Matt regularly shares his love of technology by speaking at local, regional and international conferences such as Tech Ed. Microsoft has recognized Matt as an MVP for his community contributions around connected systems technology.