A gentle introduction to AngularJS
Why a SPA?
First of all forget about web applications, a single page application is not a modern web application it is much more a fully “state full” rich client application that accidentally is written with the same technology also used to write web application and is accidentally delivered to the user via a web browser. but, that’s it.
A SPA, and I agree with John Papa’s comments on the horrible naming, is another way to deliver a rich client to the end user. So why and when should we choose a SPA as the solution to be delivered to our clients?
Generally, generally, speaking wherever we think that the benefit of having:
- a State full application;
- a host agnostic application;
- a cross browser, cross platform, application;
- an application that can be easily delivered to every device, other then computers, out there;
- …and much more…
is important we can choose to build a SPA.
When dealing with SPAs the first choice must be:
- Should I develop everything from scratch?
- Should I depend on an already developed framework?
Well, developing everything from scratch is not a big deal and it is not a big issue. I deeply know which are the problems that must be faced when developing a huge MVVM framework such as Radical and I can state that is not a complex stuff at all, but sometimes you fell like you are reinventing the wheel, especially if you take a look at what the world offers.
My framework of choice is AngularJS.
My first AngularJS sample
<!DOCTYPE html> <html> <head> <title>My First Sample</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script> </head> <body data-ng-app> <input type="text" data-ng-model="name" placeholder="Write something here..." /> {{name}} </body> </html>
Key points to look at:
- we are “attaching” AngularJS directly from the Google CDN, yes AngularJS is developed by Google;
- it is not a requirement, I prefer to have it offline in my solution basically because a lot of times I develop while offline;
- The “data-ng-app” attribute on the body, it can be put on any element generally it will be put on the html tag, tells AngularJS that from that point down to the DOM tree there is the SPA;
- The “data-ng-model” attribute on the input element tells AngularJS that the input must be data bound, in 2 way mode, with a property named “name” on the model, that in this case is implicitly defined by AngularJS itself;
- The {{property-name}} syntax that tells AngularJS to setup a one way data binding with the specified property on the model;
if we run it what we’ll see is:
As soon as we write something in the text box the AngularJS data binding engine kicks in and synchronize the changes to the “readonly” element.
Easy peasy ;-)
.m