Thursday, November 19, 2015

Custom Directive in AngularJS

Custom Directive in AngularJS : A Simplified practical approach
Concert crowd
This tutorial is about to create Custom Directives in Angular JS I feel it would be a good brain teaser if I come with some real time example. Generally we use directives in AngularJS and this is how Directives makes AngularJS so powerful. Directives are the key part of AngularJS and I belied every person works upon 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 as 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 anymore 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 shown below in short code snippet start 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: 


  1. Custom Directive Syntax: 
  1: app.directive("customDir", function () {  
  2: return {  
  3:         restrict: "E",        // directive is an Element (not Attribute)
  4:         scope: {              // set up directive's isolated scope
  5:             name: "@",          // name var passed by value (string, one-way)
  6:             amount: "=",        // amount var passed by reference (two-way)
  7:             save: "&" // save action
  8:         },  
  9:         template:             // replacement HTML (can use our scope vars here)
 10: "<div></div>",  
 11:         replace: true,        // replace original markup with template
 12:         transclude: false,    // do not copy original HTML content
 13:         controller: [ "$scope", function ($scope) {   }],  
 14:         link: function (scope, element, attrs, controller) { //define function, used for DOM manipulation }
 15:     }  
 16: });  
 17: 

The actual code implementation of the custom directive is shown below:
      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: });  
 16: 


In this example I’ve created element and attribute directive and restricted as EA. Scope means it will use the parents scope . 3rd is template which is utilizing the controller scope value as default. Hope you are familiar with scope variable .In 4th point I’ve added click event on this directive and updating the scope’s 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 as depicted below:

If I inspect an element than I can easily see that it has added into DOM as showing below in screen shot:



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





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

To know more MVC and WebApi Kindly go through with these links
MVC Articles & WCF and WebApi
Thanks.
Enjoy coding and reading








1 comment :

  1. Ver good explanation. AngularJS allows to create Custom Directives like Element Directive,Attribute Directive, CSS Class Directive etc that modify or even create totally new behaviour in HTML.

    AngularJS Training
    AngularJs Training in Chennai

    ReplyDelete