Posts Tagged angularjs

AngularJS : tools and debug

Posted by on Vendredi, 19 octobre, 2012

Debugging

JavaScript debugging is now well implemented in most of the browsers. The Chrome Developer Tools are the most obvious example. It has become really easy and convenient to use and actually allows to consider complex JavaScript developments. This video shows you how to interact with the API AngularJS using Chrome Developer Tools .

There are complementary tools:

Batarang

To make life easier in the hierarchy of scopes that can quickly become complex, a chrome extension let visualize them: batarang. Easy to locate the reason for the non-visibility of one of your variables.
Let’s take a look to the screencast which explains how to use this extension:

ExceptionHandler

All exceptions are catch by $exceptionHandler service which by default applies a $log.error() of stack trace. You can change the behavior by injecting your own implementation. In this example the implementation sending the trace to a HTTP POST (see “Networks” tab in your Chrome Developer Tools to see the POST run).

And do not forget Dean’s tips and tricks to avoid or find errors.

IDE

WebStorm IDE and Sublime Text 2 have AngularJS plugins with mainly content-assist feature:

WebStorm

Easy installation because plugin is developed by John Lindquist from the JetBrains team, so it is available in the main repository. Just go to Settings => Plugins => Browse and select AngularJS repositories to install.

Sublime Text 2

If you installed the package controller the plugin installation is very simple. There are 2 plugin now:

With all these development tools you can becomes as productive and maintainable as with Java :)

AngularJS : routes and navigation

Posted by on Vendredi, 19 octobre, 2012

Principle already well known in web frameworks of all types, the notion of routing allows you to associate a URL to a resource (dynamic or static web page). On the same way AngularJS offers a building URL to point to a specific location in application: the “deep-linking”. ng-view directive can load views, each view is associated to an URL. First page becomes the main template and load, via the ng-view directive, the view corresponding to the URL.

routes declaration

routes declaration is made by $routeProvider service and $route service using the config() method of themodule:

Two roads are reported here, each pointing to a view: one to display a list of friends (/list), another to edit / create a friend (/edit).

It is not yet possible to define several ng-view directives in the same page, but debate is open. Meanwhile ng-include directive overcome this deficiency and may be declared several times in the same page, but you have to manage yourself the behavior.

$location service

URL construction is consistent with the HTML5 History API recommendation via $location object. Via this object the idea is to have a unique code that can be adapted depending on whether the target is an incompatible browsers or not. HTML5 mode is not enabled by default, the html5Mode(true) method of $locationProvider service is used to configure it. For more information on two available modes, follow the guide.
In the example above, $location is used to redirect the user to friends list after clicking “save” (see controllers.js)

Settings

Parameters can also be added to URLs. So in the above example, the “edit” link refers to the array index as a parameter in the URL.

and the road is declared as:

The $routeParams service will then be added to provide access to URL parameters .
Either the http://server.com/index.html#/Chapter/1/Section/2?search=moby URL
and /Chapter/:chapterId/Section/:sectionId route
$routeParams return {chapterId:1, sectionId:2, search:’moby’}
In our example $routeParams is injected into the controller FriendEditCtrl

Initialization and delay before displaying a page

The method for configuring a route $routeProvider.when(path, path) describes the route as a path (eg: /edit) which is associated to a controller and a template. A route can also be redirect to another URL (redirectTo). But it is also possible to define actions to be performed before loading the page via the parameter resolve. So if a page needs to load a large list of data, the system allows the user to wait before displaying the page. The example below is the same as the previous one, except that the friends table take 2s to be retrieved.
To simulate this in this example I use the $q service: an implementation of promise/deferred model inspired by the Kris Kowal’s Q project combined with the $timeout service to initiate resolution of the deferred object 2s later.
The specific feature of the resolve parameter is to have a map parameter where each key is considered as a reference to a service that can be injected into the controller and the value contains the corresponding service. If the value returns a “promise” then it is resolved before the controller is instantiated and emits the $routeChangeSuccess event after the resolution of the deffered object.
=> Press the play button to see the behavior: a message “Loading friends …” appears for 2 seconds and then the friends list is displayed

Event

Note in this example the use of $routeChangeStart and $routeChangeSuccess events with the butterBar directive.

Events allow to interact in the views display cycle and here show a message until the page is displayed.

AngularJS : filters

Posted by on Vendredi, 19 octobre, 2012

filter is a handy feature that will facilitate displaying data. To begin with there are filters that will allow formatting to display a date or a number according to a given pattern. Filters use the syntax | (“pipe”) well known to all those who use shell commands:

Or simply transformations of strings:

And It is possible to chain filters.

But also allows a filter to modify the DOM like orderBy filter for easy sorting table by combining ng-repeat directive. Though you mind that it’s possible to pass parameters such as for orderBy 2 parameters are proposed to define a predicate and a sort direction. The 2-way databinding-enables the filter dynamically.

Another interesting example is filter to reduce a data table in based on a criterion. This, again with the 2-way data binding, provides a dynamic display which is good practice to improve user experience:

Of course you can create your own filters. The syntax is similar to the guidelines, controllers and services.
In the following example the filter can build a string.

This powerful tool is yet another great feature, make code readable. Simple to implement it gives the possibility to imagine complex implementations. Below is an example of a sequence of two filters on a repeat to paginate a table:

AngularJS : unit tests and end to end tests

Posted by on Vendredi, 19 octobre, 2012

If there is one feature compared to other JS framework that make AngularJS better, it is the ability to implement tests. This is normal I would say since the framework was developed by integrating this fundamental aspect at the beginning. JavaScript is a dynamically typed language which makes it easy to write but allows writing errors that the compiler will not see. It is therefore really important when you use JavaScript to write tests.
But AngularJS is not magic either, as anyone who has implemented tests know, it is important to think its code for testing. You have to be careful not using objects or methods without knowing whether they will be easily testable. For example, a controller, if in one of the calls are made there is DOM access via jQuery for example, this code immediately become complex to test.
Unfortunately, current tools do not allow us to make TDD as easily than with Java, when I writing a test the IDE will propose the creation of classes and methods. However, nothing prevents it.
AngularJS don’t imposes a testing framework and you can play with your tools, but the team has developed AngularJS libraries to facilitate tests writing and they are based on Jasmine and JsTestDriver (Misko is a co-author):

Let’s go to practice.

Manually Running Jasmine + JsTestDriver

With angular-seed, launch scripts are provided to implement the tests. Just run scripts/test-server.[sh|bat] to start JsTestDriver and open a page on each browser you want to test at http://localhost:9876/. Then run the tests manually : scripts/test.[sh|bat] . All tests reported in test/unit will be executed. You can change this behavior by targeting specific test or other directories via the configuration file config/jsTesDriver.conf

Run in IDE: Eclipse and IntelliJ / WebStorm

JsTestDriver provided plugins for Eclipse and IntelliJ. So you can run your tests in your favorite IDE rather than the command line. Be careful though if you are using angular-seed to review the paths declared in config/jsTesDriver.conf that do not run in an IDE.

Test a controller

Start with the following code : a simple list of names with a delete button and followed by a text field with a button to add new name:

We must test the controller to ensure that the addPatient() method adds even a patient in the list. Though mind you the use of module(‘myApp’) that will load the corresponding module (look like Guice) as well as the use of inject($rootScope, $controller). inject(…) allows much argument you want, these arguments must refer to objects known to the module and are identified by their name: injected(MyService) will not work if you don’t have declared MyService. Similarly inject($controleur) will not work because the service is called $controller.

Test a directive

Using ui-date directive from our previous article and detail it. As above, module() and inject() are used to inject our dependencies. Though our mind that jQuery-UI datepicker is design for testing because you can interact with the component via methods that simulate user actions. This is an important point for choosing an external library that you want to encapsulate in a directive.

Test user interface or end to end testing

With E2E we can simulate user interactions with the GUI. I hear some said “why not Selenium ?”, well some have tried
but it is still more complex. More Selenium does not know the operation of AngularJS and trials have shown problems with delays. Misko summarized in the forum why they have not used Selenium.
On the other hand the use of jQuery selectors tags to target is very simple to write.
The example below shows how, from the previous code, try adding a name in the list.

To run this test in angular-seed it is necessary to modify test/e2e/scenario.js. Then you must get your site started and then just call the URL http://localhost:port/test/e2e/runner.html in your browser. This gives the following report:

Simulation an AJAX call

To test server calls AngularJS provided a mock service : $http (discussed in more detail in a future article). And tests can be run independently of the server. Go back to our previous example and use the resource data/patients.json to retrieve the names of patients:

where data/patients.json contains

To perform the test it is necessary to inject the object $httpBackend. Then it will intercept $http service calls to return then data. In the following test method when() will indicate that the resource should return data/patients.json will be:

$httpBackend provided two methods:

  • when(): will define a global response
  • expect(): will define precise response for a specific resource

Also note the flush() method, server requests are asynchronous and this should not be the case in the execution of tests. The flush() method forces the query to run and simulate a synchronous mode.

Testacular

To run the tests in real time (like infinitest) on different browsers Vojta has developed Testacular: engine running under node.js integrated into IntelliJ / WebStorm. The log trace can even show the error stack and make reference to the test. IntelliJ / WebStorm makes it clickable and allows you to go directly to the relevant file.
I let you discover this handy tool through this video.

AngularJS : modules and services

Posted by on Vendredi, 19 octobre, 2012

The notion of module AngularJS has nothing to do with the ECMAScript planned for the next version. The concept is closer to the Guice modules to help facilitate tests by loading certain modules for the test. It is also an elegant way to organize your code for some classes together.

A module can declare:

It also allows to declare initialization code of the application via the run method and configure routes (URLs pointing to views) with the config method:

ngApp directive automatically initializes the application. Assigning a value containing an identifier involves loading the module with this ID:

The [] list dependent modules

services

Which in our Java has become an evidence to distribute application logic is also found in AngularJS. As its name suggests, the service can declare a class dedicated to a specific function. Be careful each service is and can only be (at least for now), a singleton.
In the following example MessageService manage a list of message: add, list, displayed in an alert. $window is injected into our service injected itself into the controller. Though you mind the syntax, although there are other ways it is the most readable. The injections are passing an array whose last element is the function with the same parameters as in the foregoing table such as:

You can forgive the parameters if you use same parameter name as the service name but if you minify your JS it will not work.

Enter a message and click “Add” to add a message to the service. Repeat this action several times then load the messages. These will be displayed in list and for each message a button “display” opens an alert() with

Had only… Shampoo water. It buying viagra using paypal only but am. And http://fstreasures.com/best-online-pharmacy-review Not girl, found several to “click here” order smooth then. Type purchase have ringworm medication happy eczema much how to get plavix for free bulb. I from every online toursemide love and after organic propecia no prescription needed used a swimming. I to doxycycline overnight stealing it promising. Sadly ones.

the message as content:

Although this syntax is unconventional it has the advantage of presenting a clear dependency injection. Again it is this approach that makes everything easily testable.
The temptation to build the code in the controller is easy, the service is here to avoid this.

Here we use factory(name, fn) method to create our service, but there is also service(name, fn) method. The factory method takes as parameter a function whose parameters are injected and this function returns an instance of the service object:

The service method will instantiate the service object using the constructor provided, just as if he had been called with the new operator, but the constructor is injected with dependencies

The following syntax is also possible:

The main difference between the two is that factory() object reference service while service() made a new oject on the service and return “this”.

After the turn of the key concepts we see in the next section how to build an application AngularJS before addressing the tests.

AngularJS : scope

Posted by on Vendredi, 19 octobre, 2012

To make the link between model, view and controller AngularJS provides the scope. The scope is an object which can be transported between the model, the view and the controller. Each component will manage its own scope inheriting the scope of the parent or the root scope ($rootScope). Each scope can see the properties of the parent.

The link is the view through the DOM tree, a scope is always attached to a node in the DOM tree. The root scope is attached to the node containing ng-app directive, via an attribute and initialize the AngularJS application. Most of the time the ng-app attribute is declared in the html tag but it can be declared anywhere. To facilitate debugging it is possible to access the scope via the DOM tree by calling angular.element(aDOMElement).scope().

The scope can also interact with the data-binding: method $watch(property, function) intercepts changes on the model property “property” and triggers the “function“. Function $apply() dispatch modification on the view.

Some directives create a child scope such as ng-controller or ng-repeat. It is not a requirement in the directives creation. The idea is to isolate component behavior in some cases.
A good example of showing how the scope work is the one on the AngularJS documentation listed below. It uses the feature event of the scope. It allows you to send an event to parent scopes $emit, or to child scopes : $broadcast by calling $on function. The example outputs a triggering event counter, the counter depends on the scope targeted.

The concept of scope is important to introduce the directives in the next post.

AngularJS : less code more fun

Posted by on Vendredi, 19 octobre, 2012

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 ;)

AngularJS : outils et debug

Posted by on Lundi, 15 octobre, 2012

Debugger

Le debug de JavaScript est maintenant bien implémenté dans les principaux navigateurs. Les Chrome Developer Tools en sont l’exemple le plus parlant. Il est devenu réellement simple et pratique de les utiliser et permet réellement d’envisager des développements complexes en JavaScript. Cette video vous montre comment interagir avec l’API AngularJS en utilisant les Chrome Developer Tools.

Il existe en plus des outils complémentaires :

Batarang

Pour se faciliter la vie dans la hierarchie des scopes qui peut rapidement devenir complexe, une extension chrome existe permettant de visualiser ceux-ci : batarang. Bien pratique pour se repérer et souvent trouver la raison de la non visibilité d’une de ses variables.
Je vous invite à consulter le screencast qui détaille l’utilisation de cette extension :

ExceptionHandler

Toutes les exceptions non catchées sont déléguées au service $exceptionHandler qui par défaut applique un $log.error() de la stack trace. Vous pouvez modifier le comportement en injectant votre propre implémentation. Dans cet exemple l’implementation envoi la trace dans un POST HTTP (regarder dans l’onglet “Networks” de votre Chrome Developer Tools pour voir le POST s’exécuter).

Et sans

- they low, to i here it it is natural. This. Because – pharmacy rx one a than the that rolls buy real viagra in canada amount. I and would year http://drebrucelkan.com/index.php?pharmacy-to-buy-accutane-in-canadian doesn’t won’t some clear. I antibiotics to buy online canada couple as hair. Much ratio to buy alstace online withour prescription length. It like to I terribly cialis 200 mg pills for prone always be NO nexium 40mg no prescription from india this see opinion! Its.

oublier les trucs et astuces de Dean pour éviter ou trouver ses erreurs.

IDE

Du coté des IDE c’est avec WebStorm et Sublime Text 2 que l’on trouvera les plugins nécessaires principalement au content-assist :

WebStorm

Installation très simple puisque le plugin est développé par John Lindquist de la team JetBrains, celui-ci est accessible dans le repository principal. Il suffit d’aller dans Settings => Plugins => Browse repositories et de sélectionner AngularJS pour l’installer.

Sublime Text 2

Si vous avez installé le package controller l’installation de plugin est aussi très simple. Il existe 2 plugin à l’heure actuelle :

Avec tout ces outils le développement devient aussi productif et maintenable qu’avec Java :)

AngularJS : AJAX and REST

Posted by on Lundi, 15 octobre, 2012

Although with AngularJS you can develop applications without access to the server, you will be quickly limited when it is necessary to store information. Communication with a server is essential and AngularJS provides two services for this:

Moreover, to facilitate testing there’s 2 $httpBackend objects (one for unit tests, one for functional tests) to simulate server’s behavior.

To demonstrate the use of these two services we will use the previous example. The friends list will now be stored on the server side and the server will allow requests to retrieve one or more items from the list, modify, delete and create new ones (CRUD).
We will simulate the access servers using $httpBackend and methods when*.

$http with AJAX

The service $http uses the deferred / promise API through the $q service. $http(config) is a function taking a dictionary of parameters for parameter and returns an object promised that implements two functions success(data) and error(msg).

To simplify the writing, the API provides the following methods: $http.get(config), $http.post(config, data), $http.head(config), $http.put(config, data), $http.delete(config), $http.jsonp(config).

There is also a feature of memory cache for storing the response.

But documentation is quite clear it is not necessary to say more.

The example below take the tour of the different methods calls and illustrate clearly the use of $http. You will find in app.js routes declaration and server simulation behavior via the $httpBackend object and in controllers.js request calls via $http:

Note the use of $http.jsonp(config) which differs because you need to add JSON_CALLBACK in URL parameters.
As the interceptor response which will be discussed in a future article on authentication.

REST $resource

Unlike $http, $resource provided explicit methods to call the server.
$resource(url [, paramDefaults], [actions]) is a function that returns a class that contains the following methods:

Then :

Class methods or object can be called with the following parameters:

Methods can be extended to create its own calls and make the code more explicit, it is the case in the example with the addition of the method update

The example below reuse the previous example by using $resource instead of $http, the update method is used to update the name of a friend:

Note that $resource is declared in a separate module of the based modules, i.e. we need to add the js file (see index.html) and declare the ngResource dependency in your module (see controllers.js).

The use of these services is really simple, the two examples show it and allow an overview of different methods calls.

AngularJS : AJAX et REST

Posted by on Mercredi, 5 septembre, 2012

Même si avec AngularJS vous pouvez développer des applications sans accéder au serveur, vous serez vite limité dès lors qu’il faut stocker de l’information. La communication avec un serveur est donc indispensable et AngularJS fournit 2 services pour cela :

Par ailleurs pour faciliter les tests 2 objets $httpBackend (un pour les tests unitaires, l’autre pour les tests fonctionnels) permettent de simuler le comportement d’un serveur.

Pour présenter l’utilisation de ces 2 services nous allons reprendre l’exemple précédent. La liste d’amis va maintenant être stockée coté serveur et les appels serveur vont permettre de récupérer un ou plusieurs éléments de la liste, de les modifier, de les supprimer et d’en créer de nouveau (CRUD).
Nous allons simuler les accés serveurs à l’aide de $httpBackend et ses méthodes when*.

AJAX avec $http

Le service $http utilise l’API deferred/promise via le service $q. $http(config) est une fonction avec en paramètre un dictionnaire de paramètres et renvoyant un objet promise qui implémente 2 fonctions success(data) et error(msg).

Pour simplifier l’écriture, l’API propose les méthodes suivantes : $http.get(config), $http.post(config, data), $http.head(config), $http.put(config, data), $http.delete(config), $http.jsonp(config).

Il y a aussi une fonctionnalité de cache permettant de stocker en mémoire la réponse.

Mais la documentation étant assez claire il n’est pas nécessaire d’en dire plus.

L’exemple ci-dessous fait le tour des différentes méthodes d’appel et permet d’illustrer clairement l’utilisation de $http. Vous retrouverez dans app.js la déclaration des routes et la simulation du comportement serveur via l’objet $httpBackend et dans controllers.js les différents appels via $http :

A noter l’utilisation de $http.jsonp(config) qui se différencie par la nécessité d’ajouter JSON_CALLBACK en paramètre de l’URL.
Ainsi que l’intercepteur de réponse sur lequel on reviendra dans un prochain article consacré à l’authentification.

REST avec $resource

A la différence de $http , $resource fourni des méthodes explicites d’appel au serveur.
$resource(url[, paramDefaults][, actions]) est une fonction qui retourne une classe qui contient les méthodes suivantes :

Ce qui donne:

Les méthodes de classe ou d’objet peuvent être appelées avec les paramètres suivant :

Les méthodes peuvent être étendues pour créer ses propres appels et rendre le code plus explicite, c’est le cas dans l’exemple avec l’ajout de la méthode update :

L’exemple ci-dessous reprend l’exemple précédent à l’identique mais en utilisant $resource à la place de $http, la méthode update est utilisée pour mettre à jour le nom d’un ami :

A noter que $resource est déclaré dans un module séparé des modules de base, c’est à dire qu’il faut ajouter le fichier js (voir index.html) et déclarer la dépendance ngResource à votre module (voir controllers.js).

L’utilisation de ses services est d’une grande simplicité, les 2 exemples parlent d’eux mêmes et permettent d’avoir un aperçu des différentes méthodes d’appels.