AngularJS : tools and debug


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:


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:


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.


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


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

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)


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


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

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

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.


To run the tests in real time (like infinitest) on different browsers Vojta has developed Testacular: engine running replica uhren 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

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


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 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 : directives and components

The concept of directive is the most interesting feature of this framework. It is also one that is closest to our web framework in Java: creating reusable components.

A directive able to (re)define HTML tags and extend the language to give the properties of a DSL (Domain Specific Language). AngularJS provided a set of guidelines as the basis for designing a web application.

How to declare a directive can vary to be adapted to the rules of HTML (XHTML, XHTML strict, etc). In the JavaScript code the syntax is the same as Java (CamelCase) which myElement can be decline in 5 way my:element, my_element, my-element, x-my-element, data-my-element . The call may be made as a tag, attribute or CSS class:


Below is an example of based directives ng-repeat and ng-include whose name clearly indicates the function. With 2 templates, defined here in script tag but could be defined in HTML files as well, it scans a table that displays these templates and get parameters. Note that parameters are loaded by inheritance of the scope properties (see previous article).

  • ng-include directive transforms a piece of HTML code into a reusable component.
  • AngularJS can compose and nest directives between them.

Most fun is creating its own directives to invent their own tags. It’s really the originality of this framework and makes a more readable code and well structured.
Begin by simply improving an input field by giving it the ability of autocompletion using the jquery-ui autocomplete.

To apply directive, AngularJS uses a « compiler« . It go through the DOM tree at startup. When it detects a directive associates it to the node. Once all directives detected for a node, the method compile() of each directive is executed according to its priority. compile() method returns a link() function that aims to define the events interactions with the element and make the link with the scope (i.e. the model) via the $watch method.

Let’s go further in defining our own tag. Start from a feature from our EMR application in the hospital. We need to have a research component for patient inside and outside the medical unit. The excellent component select2 tag improves basic sekect tag by adding a search field and corresponds perfectly. With the directive will now be able to create a dedicated tag. Let’s call finder and give it three attributes:

  • data to pass the array of objects
  • selection to define the variable that will retrieve the selected patient
  • favorite to indicate the criteria differentiating patients from other unit

The aim is that patients in the unit are displayed in the dropdown list and the others is accessible by the search field:

This time some directive settings appear, make a brief review:

  • restrict : to specify whether the declaration is tag (E), attribute (A), class (C), or comment (M)
  • template : replaces the tag with the specified content
  • replace to say if we replace the statement or not
  • scope : to create a child scope dedicated to the directive, make it possible to retrieve properties of parent scope using ‘=’, retrieve an attribute using ‘@’, or recover a function using ‘&’.
  • link : the code to assign to the select2 the input and report events that will populate the model

other parameters exist and to go further take a look to the doc .

The code is simple, well organized and readable. Everything is testable (discussed in a future article). This approach allows development of « big app » in JavaScript.

For other helper examples take a look at

As well as the excellent screencasts John Lindquist (JetBrains evangelist and when we know they are trying to work on an online IDE …)

AngularJS : scope

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

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:

{{label}} {{patient.prenom}} {{patient.nom}}

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 replica uhren 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 : AJAX and REST

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), $, 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.