Building Custom Directives using AngularJS

By ongraph
December 5, 2014 | 1268 Views

Latest Industry insights to keep you updated on the latest happenings.

What are Directives?
AngularJS allows you to extend HTML with new attributes called Directives.
“Directives are the core functions that get run when the DOM is compiled by the compiler. Directives allow you to modify the grammar of the web through reusable HTML elements, attributes, and classes”.
Angular comes with a set of built-in directives, like 
ng-app: It initializes an AngularJS application and defines the root element of an AngularJS  application (i.e. It tells AngularJS that the element on which it is applied is the owner of the AngularJS application).
ng-init: The ng-init directive defines initial values to an element in an AngularJS application.
ng-model: The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
What are Custom Directives?
Although AngularJS comes with powerful built-in directives, but still some times we want to create our own reusable functionality. so, to complete our custom requirements, AngularJs allows you to build our own custom Directives.
Directive needs to be invoked from HTML, and for this we can simply apply the directive in the DOM. we can pick one of the four methods for invoking a directive:
 There are four valid options for restrict according to the four different ways (which we saw above) to invoke a directive, so:

The restrict can specify multiple options too. If you want to support more than one as an element or an attribute, simply make sure all are specified in the restrict keyword:

Example Of Custom Directives
Custom form validation directive to compare two fields

Usage in template file



Monthly industry insights to keep you updated on latest happenings

Follow us on Twitter
Follow us on Facebook
Follow us on Linkedin