Custom Directives In AngularJS

This tutorial is about creating Custom Directives in AngularJS. I feel it would be a good brain teaser if I come with some real time examples. Generally, we use directives in AngularJS and this is how Directives make AngularJS so powerful. Directives are the key part of AngularJS and I believe every person working on angular should know its benefits.

AngularJS is bundled with powerful directives out of the box. In this post, we’ll focus on how to create your own custom directives which may be one of your project needs. Though example is simple, but idea is to understand the depth.

An excerpt from docs.angularjs.org is given below about directives is :

"At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children."

Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass. Much like you create controllers and services, you can create your own directives for Angular to use.

If you have used Angular, certainly you have confronted with keyword ng-. This is what we will discuss and create.

This is one of the already built in directive as in the following short code snippet, starting with ng-model:

  1. <input type="text" ng-model="firstName"><br/>  
Directive types

All of the Angular-provided directives match attribute name, tag name, comments, or class name. The following demonstrates the various ways a directive (myDir in this case) can be referenced from within a template:

As an element:
  1. As an element:  
  2. <custom-Dir></custom-Dir>  
  3. As an attribute:  
  4. <span custom-Dir ></span>  
  5. As an attribute:  
  6. <span class=" custom-Dir: exp;"></span>  
  7. As a comment:  
  8. <!-- directive: custom-Dir exp -->  
  9. Custom Directive Syntax:  
  10. app.directive("customDir", function () {  
  11.     return {  
  12.         restrict: "E",        // directive is an Element (not Attribute)  
  13.         scope: {              // set up directive's isolated scope  
  14.             name: "@",          // name var passed by value (string, one-way)  
  15.             amount: "=",        // amount var passed by reference (two-way)  
  16.             save: "&"           // save action  
  17.         },  
  18.         template:             // replacement HTML (can use our scope vars here)  
  19.           "<div></div>",  
  20.         replace: true,        // replace original markup with template  
  21.         transclude: false,    // do not copy original HTML content  
  22.         controller: [ "$scope", function ($scope) {   }],  
  23.         link: function (scope, element, attrs, controller) { //define function, used for DOM manipulation }  
  24.     }  
  25. });  
The actual code implementation of the custom directive:
  1. app.directive("customDir", function () {  
  2.     return {  
  3.         restrict: "EA",  
  4.         scope: false,  
  5.         template: "<div>Your name is : {{firstName}} + {{lastName}}</div>" +  
  6.         "Change your name : <input type='text' ng-model='firstName' />",  
  7.         replace: false  
  8.           
  9.     };  
  10. });  
Or
  1. app.directive("customDir", function () {  
  2.     return {  
  3.         restrict: "EA",  
  4.         scope: false,  
  5.         template: "<div>Your name is : {{firstName}} + {{lastName}}</div>" +  
  6.         "<b>Change your first name : </b> <input type='text' ng-model='firstName' />",  
  7.         replace: false,  
  8.         link: function ($scope, element, attrs) {  
  9.             element.on('click', function () {  
  10.                 $scope.firstName = "Clicked on Custom Directive !!!";  
  11.             });  
  12.         }  
  13.           
  14.     };  
  15. });  
In this example, I have created element and attribute directive and restricted as EA. Scope means it will use the parents scope. 3rd is a template which is utilizing the controller scope value as default. Hope you are familiar with scope variable. In the 4th point, I have added click event on this directive and updated the scopes first name value. As soon as you click on this directive it updates the value of first name scope variable.

If I run an application it shows the following screen:



If I inspect an element than I can easily see that it has added into DOM as in the following screenshot:



Now if I change in the text box value it works perfectly and update the value of first name whereever it is bind on html page.



Hope it will help you somewhere and thanks for reading this.