AngularJS

What is AngularJS?
(https://www.youtube.com/watch?v=MgcJe6IZcLY)

Published on 8 Sep 2015
http://zerotoprotraining.com

AngularJS – The Next Big Thing

(http://www.codeproject.com/Articles/869712/AngularJS)

AngularJS is the next big thing for web applications.

AngularJS is a framework for client side web application development that brings with it the virtues of organization, structuring and the architectural pattern that helps make enterprise and data centric business web application development a breeze.

AngularJS is an open source web application framework wrapped around native HTML/JS/CSS technologies. It augments the web development techniques with patterns and practices that helps web application development become more mature and be able to handle more and more responsiblity that can (and should be) be shifted from the backend to the frontend.

AngularJS is “Super-powered by Google” and has a active community around it so anyone starting out with Angular can except to have a super charged ecosystem already present and one can quickly get started to building cool things and have their own “WOW” moments while using Angular.

Angular comes as a natural extension to the thinking and mindset of the modern web application developer. Angular brings the power where it belongs. Angularjs is built around design principles that supports scalability, maintainability, modularization at it core. It is best suited for thick client business web applications. It encourages the usage of best practices and patterns of development and thus drives the development of a high quality decoupled modular maintainable application. It serves as a solid base for large business web applications.

What Angular provides:

  • Architecture/organization patterns out of the box (MVC/SPA/DI)
  • View templating using plain-old HTML (no new templating language to learn) for creating dynamic views
  • Allows to extend HTML vocabulary to create new UI widgets/components
  • Avoids scattered DOM manipulation spagetti code
  • Inherent support for testing of the application
  • Provides modularity, loose coupling and reusability
  • Parallel development and comprehensible code due to virtue of MVC

Design goals (quoting from AngularJS guide):

  • Decouple DOM manipulation from application logic. This improves the testability of the code.
  • Regard application testing as equal in importance to application writing. Testing difficulty is dramatically affected by the way the code is structured.
  • Decouple the client side of an application from the server side. This allows development work to progress in parallel, and allows for reuse of both sides.
  • Guide developers through the entire journey of building an application: from designing the UI, through writing the business logic, to testing.

Overall architecture in terms of MVC of an Angular appplication:

(Image from software-architects.com)

Key Features of AngularJS

AngularJS comes up with a whole set of buzzwords along with it. These buzzwords can give you a brief idea as to what to expect from AngularJS and also if you’re acquainted with them you would appreciate the virtues that these will bring for web development and how reasonable they will prove for serious web development. Some of which come rightaway to my memory are:

  • MVC/MVVM/MVW
  • SPA
  • Testing(unit/e2e)
  • DI/IOC
  • Templating
  • 2 way data-binding
  • Promises
  • Declarative UI

If we need a rock solid framework to handle our large scale web application we need all this power and AngularJS being a full-featured web framework provides us all of these and also its amazing to see how refreshingly all of this has been adapted by AngularJS in the JS realm. All of the features like testability, intuitive view templating, declarative UI design, dependency injection, separation of concerns, model view synchronization, custom components etc are the ones that web developers would expect of a framework that they will be using for building large scale maintainable business web applications. Angular being a non-opionated framework puts all these powers to the wisdom of the developer to choose how to best build a system that he intends.

Following is an image from adevedo.com that shows components of AngularJS that make it tick!

(Image from adevedo.com)

Following is a brief description of the important features in Angular:

(quoting from http://code.tutsplus.com/tutorials/5-awesome-angularjs-features–net-25651)

Two Way Data-Binding:

Two way data-binding is probably the coolest, most useful and popular feature that is present in most of the competing web application frameworks including AngularJS. Two way data binding in AngularJS handles the model view synchronization. View in a web application is a view/representation of data at a point in time and it represents a state in the data flow cycle of the web applcation. Databinding is an essential and mandatory part of any web application and it has to be handled either by application code or the framework itself. Handling two way binding manually requires considerable amount of boilerplate code which includes traversing, manipulating, and listening to the DOM. If the framework supports data-binding then the boilerplate code required for this is eliminated from the application code and lets the developer focus more on application logic.

Model act as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application. The data-binding directives in Angular provide a projection of your model to the application view. This projection is seamless, and occurs without any effort from you. AngularJS’ two-way data-binding handles the synchronization between the DOM and the model, and vice versa.

(Image from inqbation.com)

Templates

In AngularJS, plain old HTML serves as the temlating language and yes that has its benefits because it elimiates the efforts that a developer has to put in learning and getting acquainted with a new templating language and also it serves welll for designers who mostly always have HTML in their skillset.

AngularJS templates allows for designer-developer harmony because the template is easily comprehensible by both designers and developers. The designers can design the view and write HTML for it and the developers can hook into the HTML to add bindings and extend the HTML to implement the required behavior and functionlity.

Following is an example of an Angular template. The HTML vocabulary is extended, to contain instructions on how the model should be projected into the view.

<div ng-controller=”AlbumCtrl”>
<ul>
<li ng-repeat=”image in images”>
<img ng-src=”{{image.thumbnail}}” alt=”{{image.description}}”>
</li> </ul> </div>

MVC

AngularJS incorporates the basic principles behind the original MVC software design pattern into how it builds client-side web applications. AngularJS incorporates MVC in a web application in a holistic sense so that the benefits out of MVC can be reaped when scalabiliy is one of the concerns of the web application. The MVC or Model-View-Controller pattern means a lot of different things to different people. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). To settle the argument about which MV* framework AngularJS is, Igor Minar (core developer AngularJS) decalred AngularJS to be MVW framework – Model-View-Whatever. Where Whatever stands for “whatever works for you”.

  • Model

The model is simply the data in the application. The model is just plain old JavaScript objects. There is no need to inherit from framework classes, wrap it in proxy objects, or use special getter/setter methods to access it. The fact that we are dealing with vanilla JavaScript is a really nice feature, which cuts down on the application boilerplate.

  • ViewModel

A viewmodel is an object that provides specific data and methods to maintain specific views.

The viewmodel is the $scope object that lives within the AngularJS application. $scope is just a simple JavaScript object with a small API designed to detect and broadcast changes to its state.

  • Controller

The controller is responsible for setting initial state and augmenting $scope with methods to control behavior.

  • View

The view is the HTML that exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.

This division creates a solid foundation to architect your application. The $scope has a reference to the data, the controller defines behavior, and the view handles the layout and handing off interaction to the controller to respond accordingly.

(Image from w3schools.com)

Dependency Injection

(quoting from http://merrickchristensen.com/articles/javascript-dependency-injection.html)

AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test. Dependency injection enables us to write more maintainable and modular code by decoupling our objects from their implementations and also facilitates better testing by allowing us to mock dependencies in testing environments so that we only test one thing at a time.

With dependency injection, your dependencies are given to your object instead of your object creating or explicitly referencing them. Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go look for them or make them yourself. Think of it as a way of saying “Hey I need X’, and the DI is responsible for creating and providing it for you.

The main benefits experienced by adopting dependency injection are as follows:

  • Code tends to be more maintainable.
  • APIs are more elegant and abstract.
  • Code is easier to test.
  • Code is more modular and reuseable.

(Image from docs.angularjs.org)

Directives

Directives are one of the cool and fresh things to come from a web application framework. During your Angular development most of the time you’ll find yourselves around some directive. Directives give you the power to implement custom UI components/widgets that can express your application’s (domain) components clearly and succinctly. Directives can be visual, behavior or operational depending on what your application needs. Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to “decorate” elements with behavior and manipulate DOM attributes in interesting ways. Creating your application as a composition of discrete components makes it incredibly easy to add, update or delete functionality as needed. Directives are a very powerful and exclusive feature of AngularJS.

AngularJS is built around the belief that declarative programming should be used for building user-interface and wiring software components, while imperative programming is excellent for expressing business logic. and directives lets you define the UI declaratively and that helps to keep the UI markup semantic for both designers and developers.

Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngView.You can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.

Following is an old image showing some Egyptian programmers making directives to suit their needs

Testing

The AngularJS team feels very strongly that any code written in JavaScript needs to come with a strong set of tests. They have designed AngularJS with testability in mind, so that it makes testing your AngularJS applications as easy as possible. So there’s no excuse for not doing it.

Given the fact that JavaScript is dynamic and interpreted, rather than compiled, it is extremely important for developers to adopt a disciplined mindset for writing tests. AngularJS is written entirely from the ground up to be testable. It even comes with an end-to-end and unit test runner setup. The API documentation is full of end-to-end tests that do an incredible job of illustrating how a certain part of the framework should work.

You can go through the following guides from Angular to get started with testing:

https://docs.angularjs.org/guide/unit-testing

https://docs.angularjs.org/guide/e2e-testing

Have a look at http://code.tutsplus.com/tutorials/5-awesome-angularjs-features–net-25651 . It describes the above mentioned Angular features in detail alongwith code samples.

AngularJS Bootstrap Process

It would be informative to know how Angular takes hold of the application and how the magic begins to happen. The following image from danorlando.com is quite informative and explains it quite well.

Visit http://danorlando.com/angularjs-bootstrap-lifecycle-general-overview/ for more details on the process.

(Image from danorlando.com)

Learning Curve

Angular has a steep learning curve. You start with the introduction and examples at the Angular site and if you were like me who saw two way data binding for the first time you would be like oh! thats pretty cool, and that brings up a vivid and visual imagination in your mind about the things that could be done with it and how it would make your life easy as a web developer. But as you dive deep, the ghosts of apply, digest, dirty checking, link, compile, scope inheritance, factory, provider etc come to haunt you.

Angular comes with a lot of buzzwords and all of the patterns, practices and architecture that these represent may seem daunting at first for a person new to it. Initially it might appear like a monstrous spider with many scary legs to it, but not to forget that it is this spider that will eventually build a beautiful “WEB” . Starting out with it and trying a few basic examples of Angular will make you feel wonderful about it but as you go in deep it might get overwhelming at first but sooner you’ll forsee the advantages that this framework and all its “legs” brings forth.

That said, similar is the case with most of the server side frameworks, lets see a quick comparision so as to make you feel home. Lets say if you were to use any server side framework you would have to understand the patterns and practices that the framework enforces be it MVC, DI, routing, templating or other bits. So all of this is equally overwhelming in any server side framework as in Angular. All of these patterns, practices, architecture, complexity etc are for a purpose which is to produce a better application. All of this was already present in server side frameworks to handle large code bases and business applications but since now more responsibilty is shifted from backend to the frontend hence all of it is required at the frontend as well which is what Angular provides to the web developers.

Evolution of Web Development

Lets walk through the brief history of time to see how web development has progressed and where does modern web application frameworks like Angular fit in.

  1. The history of web development goes back with the history of the internet where initially HTML was used to serve up static content and that was the era of static pages.
  2. Then came CGI (Common Gateway Interface) and the era of dymanic content. CGI was used to generate dynamic content on Web pages and Web applications.
  3. Then came the period where we had dynamic sites where the contents of the HTML page were rendered dynamically depending on the context by some backend interpreter like PHP/ASP/JSP/ColdFusion etc and the dynamically generated content was just rendered by (thin) clients.
  4. And then along the way came flash/silverlight which targetted to bring the web applications at par with desktop applications.
  5. Then came AJAX which made its mark and allowed to shift the control from server side to client side. Ajax was used in conjunction with server side frameworks where presentation logic was scattered on the server side and client side both. It marked the beginning of a different approach to web development where the client would selectively request the data from the backend and then manipulate the data on the clientside and render it as required.
  6. Then finally came HTML5 which targetted the overall enhancement of the browser and its capabilities. It introduced enhancements to HTML, the JS API and the CSS styling model. All of this promised a more mature and capable programming and development environment on the client side. With these advancements, the web progressed towards development of Rich Internet Applications (RIA). RIA being a natural extension to its desktop based GUI couterpart that were used for interfacing the software to the end user.
  7. And then to handle more complex applcations on client side leveraging the power of enahnced browser APIs, came the frameworks that would support development and manintainence of large applications. In a short span of time, we were flooded with a large number of frameworks that helped to build complex business web applications. These frameworks helped implementing popular engineering patterns and practices (MVC/SPA/DI etc) that would serve the needs of modern web applications.

The web clients that were previously called thin clients are now transforming into thick clients. Previously, most of the logic required for serving up rendered content was handled at the backend/server with different languages/frameworks and the clients were just thin clients that rendered the content received from the backend and sometimes would add minor interactivity. But now the scenario is changing, the frontend client (browser and JS) is capable enough to handle complex computation activities so now its more appropriate and high time to shift the responsiility where it belongs i.e all of the presentation logic should be handled by the frontend.

The HTML5 and future versions lay down the spec that make browsers more capable, supportive and progressive. The browsers progressed technically and performace wise and so should we. You can still do without using the modern frameworks and their sophistication but as a modern web application developer, you need to use better tools to handle the complexity and so we should always tend to move towards progression. Also since being a developer/coder you should always find cool ways to do things and bring style to your thinking and way of doing things.

I see the evolution of web application development analogical to that of a high speeding racing car which would need good steering controls to get through the race successfully instead of crashing. As the market gets more demanding the applications will get more and more complex and so we will need good control over our application and this control is what the modern web application development frameworks offer.

Development in Web relies on open standards HTML/CSS/JS and there are multiple ways and toolset/frameworks that can be used to accomplish the task at hand. But sometimes it is better to abstract away the native coding style and introducing a framework that would help in doing it fast and better and keeping it organized and understandable during its journey from inception to completion and that is where AngularJS fits in.

JS MVC frameworks

(Image from smashingmagazine.com – Journey Through The JavaScript MVC Jungle)

(quoting from https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)

MVC (Model-View-Controller) is a software architecture design pattern. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. The MVC design pattern allows for separation of concerns (SoC). MVC design pattern allows to segregate the application into three major parts categorzied by their different concerns – Model, View and Controller. The modern JS frameworks provide developers an easy way to organize their code and enforce the SoC (Separation of Concerns) software design principle using variations of MVC .

MVC offers architectural benefits over standard JavaScript — it helps you write better organized, and therefore more maintainable code. This pattern has been used and extensively tested over multiple languages and generations of programmers.

MVC separates the concerns in an application down into three parts:

  1. Model: Models represent the domain-specific knowledge and data in an application. It is where the application’s data objects are stored. The model doesn’t know anything about views and controllers. When a model changes, typically it will notify its observers that a change has occurred..
  2. View: Views are typically considered the User-interface in an application (e.g your markup and templates). They should know about the existence of Models in order to observe them, but don’t directly communicate with them.
  3. Controller: Controllers implement the presentation logic of the application. The controller is the decision maker and the glue between the model and view.
(quoting from https://developer.chrome.com/apps/app_frameworks)

(Image from developer.chrome.com)

MVC frameworks come in different flavors and variants and most of the MVC frameworks implement one of the variants of MVC. The frameworks may not follow the patterns strictly but target to implement the core underlying principle of Separation of Concerns. The frameworks tend to mix and match other components in the MVC set and delegate functionality differently to different components of MVC as they seem fit and affective for the target application/developer audience. Some of the popular flavors of MVC are:

  • Classic MVC
  • Model 2 (MVC adapted for Web Applications)
  • MVP (Model View Presenter)
  • MVVM (Model View ViewModel)

All of the frameworks that implement the MVC pattern in some way are tend to categorized as MV* frameworks. MV* is an umbrella term encompassing all frameworks implementing MVC or some variant of it. Most of these frameworks are likely to have a Model component and View component and other component(s) to bind the whole architecture (be it controller or presenter or viewmodel), hence they are named as MV* frameworks.

Regarding the variant of MVC that AngularJS implements, following is shared by Igor Minar (one of the developers of AngularJS): For several years AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it’s now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller. Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers. The overall intention of implementing the MVC pattern or its variants is to allow for separation of concerns, So to settle the argument about which MV* framework AngularJS is, Igor Minar (core developer AngularJS) decalred AngularJS to be MVW framework – Model-View-Whatever. Where Whatever stands for “whatever works for you”. (quoting from https://plus.google.com/+AngularJS/posts/aZNVhj355G2)

The following links throw more light on the different MVC frameworks:

Why use a JS MVC framework

Lets review the differences between traditional web application architecture and a MVC based web application architecture.

Kris Zyp has written an excellent article on client server model for the web where he contrasts the advantages of modern web client server model to the traditional one. I suggest you to give it a read here https://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/ at Sitepen. Also there is a different article by Peter Svensson which is more or less the same but in a different context. Have a look at it here. Following section extends upon this in context of JS MVC frameworks.

Traditional Web Applications

(Image from sitepen.com)

Traditional web application development has distributed the implementation of the user interface across the network, with much of the user interface logic and code executed on the server (thin client, fat server). This has several key problems:

  • Poor distribution of processing – With a large number of clients, doing all the processing on the server is inefficient.
  • High user response latency – Traditional web applications are not responsive enough. High quality user interaction is very sensitive to latency, and very fast response is essential.
  • Difficult programming model – Programming a user interface across client/server is simply difficult. When every interaction with a user must involves a request/response, user interface design with this model is complicated and error prone. The vast number of web frameworks for simplifying web development testifies to this inherent difficulty. Some have mitigated this difficulty to some degree.
  • Increased vector of attack – Unorganized mingling of user interface code with business code can increase security risks. If access rules are distributed across user interface code, as user interface code grows and evolves, new vectors of attack emerge. With mixed code, new user interface features can easily create new security holes.
  • Heavy state management on the servers – When client user interface state information is maintained by the server, this requires a significant increase in resource utilization as server side sessions must be maintained with potentially large object structures within them. Usually these resources can’t be released until a session times out, which is often 30 minutes after a user actually leaves the web site. This can reduce performance and scalability.
  • Offline Difficulties – Adding offline capabilities to a web application can be a tremendous project when user interface code is predominantly on the server. The user interface code must be ported to run on the client in offline situations.
  • Reduced opportunity for interoperability – When client/server communication is composed of transferring internal parts of the user interface to the browser, it can be very difficult to understand this communication and utilize it for other applications.

JSMVC Web Applications

(Image from sitepen.com)

JS MVC based web application architecture focuses on moving presentation logic from server to client and enabling implementation of a thick client web application. The advantages of a clean client/server model where presentation logic and code is delegated to the browser:

  • Scalability – It is quite easy to observe the significant scalability advantage of client side processing. The more clients that use an application, the more client machines that are available, whereas the server processing capabilities remain constant (until you buy more servers).
  • Immediate user response – Client side code can immediately react to user input, rather than waiting for network transfers.
  • Organized programming model – The user interface is properly segmented from application business logic. Such a model provides a cleaner approach to security. When all requests go through user interface code, data can flow through various interfaces before security checks take place. This can make security analysis more complicated, with complex flows to analyze. On the other hand, with a clean web service interface, there is well-defined gateway for security to work on and security analysis is more straightforward, holes can be quickly found and corrected.
  • Client side state management – Maintaining transient session state information on the client reduces the memory load on the server. This also allows clients to leverage more RESTful interaction which can further improve scalability and caching opportunities.
  • Offline applications – If much of the code for an application is already built to run on the client, creating an offline version of the application will almost certainly be easier.
  • Interoperability – By using structured data with minimal APIs for interaction, it is much easier to connect additional consumers and producers to interact with existing systems.
(quoting the above from http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/)

So the above comparision correctly reflects on the advantages of having presentation and application logic separated between the client and the server. For implementation of business web applications, the adoption of these patterns and separation of concerns and responsibilities between the client and the server prove to provide real benefits in terms of manageability, maintainability and agility. To have these benefits we need to move the logic/code where it belongs and when more and more logic is shifted towards the client, we need a way to structure and organize it and that is where JS MVC  frameworks come to the rescue which help in separation of concerns for web application components on the client side.

The traditional and tempting (easy to get started with) approach when starting out on a project is to drop in a few scripts, experiment and apply custom coding patterns/practices and code organization schemes which the developers assume and hope to provides maangeability and long term sustainability, which evolves and changes as the the project does costing us lots of time , use some DOM manipulation library like jquery, create event handlers/callbacks and wire all of this together. Using this style for development for a large scale web application will eventually lead to spaghetti code which will be harder to manage and maintain and will eventually slow down the speed of development and becomes a drag as the application code increases. Such development methodology is extremely dangerous when working in a big team or when the project is long-term and will be dealt by new developers or teams in the future. Since custom coding styles, custom organization and structuring is used, it introduces a steep learning curve to get acquainted with the code base and it may also lead to a stage where the application fails to scale with new requirements.

Following statistics from https://developer.chrome.com/apps/app_frameworks depicts the increase in client side code:

(Image from developer.chrome.com)

Since now more of the logic is shifted to the client and there is an increase in deployed javascript (as evident from the statistics above), we need a framework to base all of this on.  When dealing with large-scale projects, forseeing required maintability you may even roll out your own way of organizing and structuring the codebase in an attempt to make it scalable and manageable. Instead of “re-inventing the wheel”, using a JS MVC framework like AngularJS would save up lots of time and effort and will lead to decreased development and maintainence costs for the application. Using a JS MVC framework will allow for implementation of the web application using standard and tried patterns and practices that have proven to be successful. Having standards based MVC design architecture in place will also increase the comprehensibility of the web application and new teams and developers could get acquainted and get started with it easily.

Client/server architecture for modern web applications

Now that we have more capable browsers and more mature API, there is a noticable shift in web applcation development where more of the application logic is now hosted on the client and the probems and concerns that belong to the client are handled by the client itself. JS MVC frameworks encourage to move presentation logic from server to the client and enable the implementation of RIA (Rich-Internet-Apllication).

Resulting form this shift is the transformation of the client server model for web applications. Following illustration from http://stuartsierra.com/2008/07/07/moving-the-c-in-mvc depicts this notable difference in client/server architecture of traditional web applications and modern JS MVC based web applications.

(Image from stuartsierra.com)

Modern advancements in web development and technology have been the impetus for many of web development frameworks to emerge. Usage of JS to handle client side concerns (and more) is not also the need of the hour but also incresingly popular and trending.

JS as a open scripting langugage has been around for quite some years now and so is a very popular scripting language. Since JS being a popular langauage there is an evident increase in fullstack JS frameworks which handle all levels of a web application be it server side or client side using pure javascript. The fullstack frameworks are the realization of the dream/principle of “One Language Everywhere” and these JS fullstack frameworks project JavaScript as the one language that can be used everywhere.

Other than the client-server model that we are discussing here where the usage of Javascript has spawned from client to the server, we now also see native desktop applications being built with javascript. The two popular tools in this domain are NWJS (node-webkit) and Electron which help development of desktop application using web technologies. There are already a large number of such sophisticated applications out there, some of the ones you may already know are:

One of the popular server side JS frameworks that most of us are aware of and is used by most of the frameworks is NodeJS. NodeJS deserves a special mention because it was the first to make JS available for server side programming and open the doors to many more possibilities for JS. Just as food for your thought, there is this nice text written on how paypal uses nodejs, give it a read here.

Most of the fullstack JS frameworks contain a mix of the following components:

  • A client side JS framework like Angular/Backbone/Require or other
  • NodeJS as backend application server
  • MongoDB or other document databases based on JS model

Alejandro Hernandez has written a nice article titled “An Introduction To Full-Stack JavaScript“. Give it a read here. Following is an image from that article which reflects on full stack javascript frameworks:

Following are some of fullstack frameworks that can be put to use:
https://www.meteor.com/
http://mean.io/#!/
http://meanjs.org/
http://deployd.com/
http://derbyjs.com/
http://sailsjs.org/#!/

Handling of complex problems and the shift of application logic to the client demands solid foundation to lay the application on. Handling all of the data and presentation logic necesitates the need of framework that would assist in rapid deveopment whilst keeping it manageable, organized and structured. One of the model which has lately been the popular choice for structuring a business application containing both server and client parts is the one having a RESTful API at the backend that serves the data/model to the client as JSON and a MVC framework at the client side that handles the applicaton further.

Following image from an article tited “Introduction to JavaScript MVC Frameworks” written by Mukhtar depicts this model of Client-side MVC with server-side RESTful API

(Image from mukthar.com)

Following image from the article http://www.100percentjs.com/visualizing-modern-web-development-stack/ by 100percentjs visualizes the Data Flow for modern web development client server model

(Image from 100percentjs.com)

Comparision of AngularJS with other JS MVC Frameworks

AngularJS has already won the war against other JS MV* frameworks. It has proved itself to be the most mature of all JS MV* frameworks. Following are some statistics to prove this statement.

  • Community Support

(Statistics from Github.com)

(Statistics from StackOverflow.com)

  • Interest over time

(Image from google.com/trends(January 2011 – January 2016)

(Image from google.com/trends(Last 12 months)

(Image from trends.builtwith.com)

(Image from trends.builtwith.com)

(Image from trends.builtwith.com)

(Image from codebrief.com)

(Image from tutsplus.com)

(Image from infoq.com)

(Image from infoq.com)

  • Job Trends

(Image from indeed.com)

Comparision of AngularJS with enterprise toolkits like DOJO

Dojo Toolkit:

(quoting from https://en.wikipedia.org/wiki/Dojo_Toolkit)

Dojo Toolkit is an open source modular JavaScript library (or more specifically JavaScript toolkit) designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites. Dojo is a Javascript framework targeting the many needs of large-scale client-side web development. For example, Dojo abstracts the differences among diverse browsers to provide APIs that will work on all of them. It establishes a framework for defining modules of code and managing their interdependencies; it provides build tools for optimizing JavaScript and CSS, generating documentation, and unit testing; it supports internationalization, localization and accessibility; and it provides a rich suite of commonly needed utility classes and user-interface widgets.

  • Community Support (Github Statistics)
AngularJS DOJO
Watchers/Stars 47351 787
Forks 22113 389
Contributors 1415 80
Releases 161 168
  • MVC

MVC is at the core of Angular and it has been developed along the lines of the MVC design principle. AngularJS does not strictly adhere to MVC but loosely maps  to MVVM (Model-View-ViewModel) and hence it is sometimes referred to as MV* framework. Angular provides built-in inherent support for MVC design pattern to be used in building web application.

(quoting from https://dojotoolkit.org/reference-guide/1.10/dojox/mvc.html)

Dojo provides standalone tools from its toolkit for implementing MVC in a JS application. Dojo does not provide a holistic realization of MVC in a JS application and hence it allows to optionally include its MVC tool/component wherever required in the application. Dojo provides MVC functionality through dojox/mvc package. The dojox/mvc package focuses on View to Model data binding concerns on the client, it deals with data binding/controller concerns within a View, but does not deal with application level concerns that span multiple Views (such as navigation).

Application level concerns in a MVC application like routing, navigation etc. have to dealt by a different package (dojox/app) in Dojo whereas these concerns are dealt inherently by the AngularJS framework.
The status of dojox/mvc is still “Experimental” and yet not stable as indicated here (http://dojotoolkit.org/reference-guide/1.10/dojox/index.html#dojox-index) whereas Angular is more proven, stable and much mature as a MVC (JS) framework.

  • SPA

AngularJS is popular as a full featured SPA framework . AngularJS provides inherent features that support the development of Single Page Applications. Angular supports SPA through the following features it provides:

  • Nested Views
  • Controller inheritance
  • Routing
(quoting from https://dojotoolkit.org/reference-guide/1.10/dojox/

Dojo provides provisions for building Single Page Applications through its Dojox/app package. It is small application framework providing a set of classes to manage the life-cycle and behavior of a single page application delivered to a mobile or desktop platform. It is an application framework designed to simply configure through a configuration file an application formed of potentially nested views and to facilitate the transitioning between those views.

Angular’s implication of SPA is very well integrated with the full framework and with the MVC capabilities it provides i.e all the routing, controller, views and SPA pattern are tied together whereas Dojo’s Dojox/app is a standalone component that does not integrate SPA with MVC tightly and thus Dojox/mvc has to be used and configured with Dojox/app to manage a workaround of the functionality that Angular provides inherently and easily.

  • UI widgets and libraries
(quoting from https://dojotoolkit.org/reference-guide/1.10/dijit/)

Dojo provides an extensive set of widgets (user interface components) and the underlying system to support them. Dojo’s UI Library is called Dijit and lives as a separate namespace “ dijit”.

Angular does provide a UI widget toolset but not as extensive as to what Dojo provides. Angular allows to use any of the popular third party UI libraries. Angular provides a UI library named “Angular-UI” that contains different widgets, modules that encompass popular 3 rd party libraries and UI-Bootstrap module that exposes all of the Bootstrap framework widgets as angular directives.

Since Dojo is a toolset, each of its tools can be used in isolation without requiring a Dojo ecosystem around it and hence Dojo’s Dijit and other popular UI and widgets library like JqueryUI and other jquery or js plugins, can be used in an Angular application by wrapping them in directives.

  • RESTful Interation

AngularJS provides RESTful interation through the usage of angular-resource (ngResource) module that represents a REST resource and provide helper methods  (GET/POST/PUT/DELETE) for performing RESTful interaction easily. Other alternative modules are also available.

(quoting from https://dojotoolkit.org/reference-guide/1.10/dojo/store/JsonRest.html)

Dojo provides RESTful interaction through dojo/store/JsonRest . It is a lightweight object store implementation of an HTTP-based client with RESTful data interaction capabilities.

Both AngularJS and Dojo provide comparable RESTful interaction capabilities.

  • Maintainability

AngularJS provides provisions to develop maintainable applications that have huge code base. Some of these provisions are:

  • AngularJS encourages and enforces to minimize DOM manipulations and recommends to perform DOM manipulation only from directives that can be used in HTML thus avoiding spaghetti code resulting from extensive DOM manipulations and DOM events etc. that are hard to debug and trace in large web applications. Angular directives also help to increase the semantics of the HTML.
  • Angular provides features like modules that lets the application developer package different parts of the application logic as modules to increase modularity and maintainability of the application.
  • Angular provides features like DI (Dependency Injection) design pattern inherently that help in maintaining modularity and comprehensibility of the application.
  • Project structure scaffolds are available for AngularJS for development of maintainable enterprise web application.

Dojo does not provide mechanisms to minimize DOM manipulations and thus for large web applications, DOM manipulations tend to increase the chances of “spaghetti” code in the application and thus it affects the maintainability of the application. Dojo supports modules (AMD) but does not provide the DI pattern for the web application. (quoting from https://dojotoolkit.org/documentation/tutorials/1.10/modules/)

  • Data binding and View templating

The data centric nature of business web applications require data from the model to be reflected and synchronized with the UI. For a business web application dynamic views have to be created depending on the model data. Angular provides fairly easy and inherent mechanism to declaratively write dynamic views that are bound to the model data (quoting from https://docs.angularjs.org/guide/templates) In Angular, view templates are written with HTML that contains Angular-specific elements and attributes. Usage of HTML as the templating language make it fairly easy for developers to create and comprehend views. Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser. Angular uses its 2-way binding feature to keep the UI and the model synchronized.

Similar feature can be made to work in Dojo but they do not come natural with the flow of Dojo toolkit and the ease and subtleness of this feature is lost.

  • Declarative user interface

AngularJS promotes declarative design for HTML views. Usage of HTML as the templating language in the views makes it fairly easy for developers to create views and also increases the understandability and semantics of the view for the end-user as well as for a fellow developer. Angular provides a feature called “directives” that allows for enhancing HTML and customizing it to fit according to the needs of the application domain.

Declarative design can be enforced in a Dojo application by using data-* attributes but it is not comparable to Angular’s “directive” feature.

  • Better IDE and Browser debugging support for AngularJS

Netbeans IDE also provides built-in support for AngularJS to allow for easy development for web applications built with AngularJS. (http://wiki.netbeans.org/NetBeans_80_NewAndNoteworthy#JavaScript)
The Angular team also built a plugin for the Google Chrome browser called Batarang, that improves the debugging experience for web applications built with Angular. The extension aims to allow for easy detection of performance bottlenecks and offers a GUI for debugging applications. (quoting from https://en.wikipedia.org/wiki/AngularJS)

  • Difficult to enforce code uniformity in a large team when using Dojo

The programming model in Dojo is to use widgets and pin your code in them as you extend them. You are still programming to manipulate the dom and hooking up/registering/deregistering events. Dojox/mvc does not come nearly as close in producing a modular code. There are more than 2 or 3 ways to do the same thing in Dojo some of those are even bad practices but not been cleaned up (quoting from http://dojo-toolkit.33424.n3.nabble.com). So since Dojo does not provide a holistic framework towards development of modular and uniform web application, its difficult to enforce code uniformity in a large team.

AngularJS provides a holistic framework with MVC at its center and a programming model that allows for uniformity, comprehensibility and modularity. AngularJS provides isolated components injected as dependencies to other components. View, models and controller concerns cleanly separated. Better testability due to well defined componets. Directive for handling custom UI and DOM manipulations. Model manipulations through logic and UI updates through 2 way binding. Support for modules. MVC is at the center of this web applicaiton framework and thus it maintains a level of code uniformity in a large codebase.

AngularJS 2.0 Roadmap to the future

(quoting the below from http://angularjs.blogspot.in/2014/03/angular-20.html)

AngularJS 2.0 is still in design and prototyping stage as of now. But Google has announced where the journey is going. Currently its in design phase and hence some of the features or ideas discussed here will happen differently or not at all in the final product. Here are a few keys areas and design considerations that are laid out in this roadmap.

Please refer to these links for complete information:

http://angularjs.blogspot.in/2014/03/angular-20.html

https://drive.google.com/?pli=1#folders/0B7Ovm8bUYiUDR29iSkEyMk5pVUk

  • Targetted Device

AngularJS 2 is a framework for mobile apps.  It is for desktop as well, but mobile is the hard bit that we will get right first.  The AngularJS you know and, hopefully, love will still be there with data-binding, extensible HTML, and a focus on testability.

  • Targetted Browser

AngularJS is being designed for the future by targeting modern browsers and using ECMAScript 6.

Modern browsers means the set of browsers known as ‘evergreen’ or always automatically updated to the latest version.  Building for these browsers let us drop many hacks and workarounds that make AngularJS harder to use and develop on than it needs to be. Yes, there are still older browsers in use, but AngularJS is targetted towards these newer models as they will be the primary ones in use by the time AngularJS 2 is ready.

ECMAScript 6 +A (design)
All code in AngularJS 2 is already being written in ES6.  As ES6 doesn’t run in browsers today, we’re using the Traceur compiler to generate the nice ES5 that runs everywhere.  We’re working with the Traceur team to build support for a few extensions like annotations and assertions.  We call this set of extensions “ES6 +A”.

  • Performance

One of the design considerations in this roadmap for AngularJS is to make AngularJS applications perform faster. The areas that will be analysed and modified to increase performance:

Faster change detection

AngularJS apps are built around data-binding between DOM and JS objects.  The speed of AngularJS apps is driven largely by the underlying change detection mechanism we use.  Native Ecmascript’s Object.observe() API will be used for change detection to speed up perfromance.

Instrumentation

The other half of the performance equation is the code that you write.  For this, high resolution timing details of where time gets spent in your application will be provided.

Modularity

When we released AngularJS 1.0, the features were in a take-it-or-leave-it single package.  You incur the download price for every piece whether you use it or not.  Though the whole of AngularJS is very small by desktop app standards, this can make a big difference on mobile devices. For performance and to enable innovation, our goal is that almost every piece of AngularJS should be optional, replaceable, and even used in other non-AngularJS frameworks.  You’ll be able to pick and choose the parts you like and write or select others that you like better.

Other Performance topics

Though there are no designs yet, there are many other areas of performance optimization that will be included in AngularJS.  From increasing first-load time with pre-parsed templates to ensuring silky smooth 60 frames per second animations, Heavy investment will be made on a fully optimized user experience.

  • Complexity

Attempts will be made to make the API more simpler to comprehend and code so as to provide a smooth learning curve for developers. Some key areas of focus will be:

Dependency Injection

Dependency Injection is still a key differentiator between AngularJS and other client side frameworks in eliminating much of your application’s wiring code and making testability-by-default a reality.  We’ll see a less complex DI by eliminating the config phase, simplifying the syntax by using declarative-style ES6+ annotations instead of imperative.  We’ll enjoy greater capabilities by integrating DI with module loading through ES6 Modules.  We’ll also see the ability to lazily-load parts of our JS through child injectors.

Templating and Directives

The ability to specify templates directly in HTML and extend its syntax are the bread and butter of AngularJS.  Some of the goals for AngularJS’s template compiler in version 2 are:

  • Simplify the directive API
  • Integrate with other component frameworks using web standards
  • Improve performance
  • Allow tools like IDEs to analyze and validate templates
  • Enhancements

The focus will on making the elements more capable and addition of new features. Some of the key areas are:

Touch animations
Users are accustomed to certain touch aware usage patterns. E.g. scroll through a list using their finger, circle through pictures in a carousel, remove list entries by swiping them away. However:
Current implementations of carousel, infinite scrolling, … don’t share a common core and by this have a lot of redundancy and different approaches. These scenarios will be given first-class support for the best user experiences possible in your applications.

Router

The initial AngularJS router was designed to handle just a few simple cases. Anslysis of known use cases and other router implementations across many application frameworks is being done so that a simple yet extensible router that should fit the widest set of applications can be delivered.

A few cases that that are more likely to be supported are:

  • State-based routing
  • Integration with authentication and authorization
  • Optionally preserving state of some views.  Particularly needed for mobile!

Persistence

Beyond AngularJS’s humble $http, many developers have desired a higher level abstraction for working with data from servers and local persistent data in the browser. Mobile apps need to work in an “always offline” mode with syn to the server.  RESTful services need more than what is provided in $resource.  Some data can be updated in batches while some needs a continuous streaming model. In this new persistence layer, a clean structure for these cases will be provided.

Conclusion

This article intends to get us all informed where the future of web application world is heading. It attempts to provide an overview of the correct intuitive way to structure and design a web appliaction that fits naturally to the gears of the web.

The article provides an overview on the usage of JS MV* frameworks on the client side and why does a web application woven around a client side MVC framework is the best fit for implementation of a web application.

The article focuses on analysing and summarizing a comparative on the mature client side MVC frameworks out there by provding statistical information about them and helping you and your team decide over the client side MVC framework to choose for your next web applcaition.

This article is opinionated towards AngularJS framework. You can have different preference for the client side MVC framework to choose from but for me AngularJS is my personal favorite and a clear winner amongst other client side MVC frameworks.

References

https://angularjs.org/
http://trends.builtwith.com/javascript
http://www.infoq.com/research/top-javascript-mvc-frameworks
http://danorlando.com/angularjs-bootstrap-lifecycle-general-overview/
http://www.smashingmagazine.com/2012/07/27/journey-through-the-javascript-mvc-jungle/
http://www.scottlogic.com/blog/2013/12/06/JavaScript-MVC-frameworks.html
https://developer.chrome.com/apps/app_frameworks
http://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/
http://www.100percentjs.com/visualizing-modern-web-development-stack/
http://stuartsierra.com/2008/07/07/moving-the-c-in-mvc
http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/
http://code.tutsplus.com/tutorials/5-awesome-angularjs-features–net-25651


First baby steps with Angular.js
(https://www.webcodegeeks.com/javascript/angular-js/first-baby-steps-with-angular-js/)


Single Page Apps
(http://www.webcodegeeks.com/javascript/angular-js/single-page-apps/)

Single Page Apps are becoming increasingly popular as the demand for highly responsive apps is increasing. We could be using Ajax and Javascript to do this, but we will be using Angular as it is a structural framework for dynamic web-apps, efficient and easy to use, as described by the people who built it.

We’re going to create a simple app with only a homepage, an about page and a date page, so as to not need to refresh the page to view changes, but have it reflect them immediately.