AngularJS : less code more fun

This entry was posted by on Vendredi, 19 octobre, 2012 at

The main idea behind AngularJS is based on the fact that HTML was not designed to develop applications. To fill this gap proposing to extend the framework to insert HTML tags and his own behavior and to incorporate the notion of dynamic views. Unlike other frameworks the notion of template does not exist because the template is HTML, HTML is the view.

The project was designed by Misko Hevery, Igor Minar and Vojta Jina from Google. All three original Java developers. Misko is one of the lead tests at Google, tests have therefore an important part of the project design. This is notably one of the reasons why dependency injection is integrated in the framework through the notion of module. The principle is that everything is testable. This is one fundamental difference with other frameworks and that’s makes it even more relevant.

Now let’s coding: A model with a “Patient” object, a view with a basic HTML page and a controller linking both:

The model:

The view:

The controller:

Which gives:

This example shows the clearness and simplicity of the implementation of the MVC pattern and the presence of implicit data-binding. Note that there is no “main()” method. The statement attribute ng-app initializes the application. Then it is built through a series of “modules” that can be of 4 types: controller, service, filter, directive.

Now introduce a date. This is a good test to analyze a framework. The problem is the treatment of Date type which implies a conversion. A classic in our Java frameworks mostly managed by a component for entering a date and display it. For AngularJS, on UI side, “filters” allow a simple way formatting values. For input data there’s nothing, AngularJS is not a component framework. You must create a component to enter the date. This is rather a good thing than imposing how to enter a date by the framework, because often it’s depend on the context. AngularJS offers only basic components and offers the possibility of using a library of external components. A project schedule is created to allow all components to offer: angular-ui .
Now go to the implementation and introduce the notion of “directive” that transforms an input[type="text"] in a component input date simply by using the attribute “ui-date.” The code remains readable, the treatment-related date was deported in the “directive which use, in this example, jquery-ui:

Ideally it ensures the good working of the directive by a test:

Then free to change the behavior of the component, as shown below by replacing with an input mask:

HTML has not been changed. All the logic is in the component uiDate which is an extension of the input element. It’s clear and well-structured, easily testable and reusable.

But what is this “$scope” and what does it do?
What other options for designing components?
We’ll keep it for the next article ;)