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.
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 .
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 …)