Creating Custom Directives in Angular JS

Posted By : Manish Gupta | 28-Feb-2018
A Directive in AngularJs is a marker on the DOM(Document Object Model) element like attribute, element name, CSS class or comment which tells AngularJs HTML compiler i.e $compile to bind a particular behaviour (using event listeners) to that DOM element or transform that element or its children as per the requirement. 
 
AngularJs provides some in-built directives like ngBind, ngClass and ngModel. We can also create out own custom directives to meet out requirements as we will see below. During the Angular's HTML compilation process, it attaches these directives to the DOM elements to create an interactive behaviour. In order to attach the directives to the elements and/or element attribute name using Angular's Normalization process. 
 
The process of Normalization says:
1) Strip out the "x-" and "data-" prefix from the element
2) remove the "-", ":" and "_", and then convert to camelCase
 
For example:
We can use ngBind(normalized name) directive in any of the below form
1) <div ngBind="phoneNumber"></div>
2) <div ng-bind="phoneNumber"></div>
3) <div ng:bind="phoneNumber"></div>
4) <div ng_bind="phoneNumber"></div>
5) <div data-ng-bind="phoneNumber"></div>
6) <div x-ng-bind="phoneNumber"></div>
 
It is adviced to use the dash-delimited format  for the directives i.e, <div ng-bind="phoneNumber"></div>
 
In order to create a new directive we need to register it on the angular application module in the same way as we register a controller on the module. To register a directive angular provides module.directive API. This module.directive API accepts the normalized name of the directive followed by a factory function. Factory function returns an object having different options to tell the angular's HTML compiler ($compile) the behaviour of the directive whenever matched.
 
Example demonstrating the use of Directive:
Step 1: Create an HTML file as in step 1.

Include these scripts in the head element,
 
  script 1 :  PATH OF ANGULAR
  script 2 : myScript.js


 
Step 2: Create a myScript.js file which actually create a directive (function(angular) { 'use strict'; angular.module('sampleDirective', []).controller('myController', ['$scope', function($scope) { $scope.customer = { name: 'Jack', address: '123 Gurgaon' }; }]).directive('customDirective', function() { return { template: 'Name: {{customer.name}} Address: {{customer.address}}' }; }); })(window.angular);
 
 
 
---------
Thanks
---------

About Author

Author Image
Manish Gupta

Manish is a Java Developer with hands on experience in Core Java, JSP, Spring framework, JavaScript, JQuery, HTML, CSS, and SQL/PL-SQL. Tools used: Eclipse, Netbeans, DBeaver, Oracle SQL Developer, Toad, MS SQL Server. He is a keen learner and technology

Request for Proposal

Name is required

Comment is required

Sending message..