Monday 7 December 2015

Angular directive lifecycle


Lifecycle of AngularJS directive. 

AngularJS comes with rich set of in built directives which adds a specific behavior to the HTML markes by transforming the DOM elements.
Some examples of directives are ngBind, ngModel.

AngularJS provides a way to create custom directives as well.

In this tutorial we will understand the directive life cycle and how we can create the custom directive in the consecutive one.

In case of ng-app directive, AngularJS is initialized automatically as soon as HTML document is loaded. AngularJS looks for the directive "ng-app" in the HTML elements. This element then becomes the root of the angular application. "ng-app" directive auto initializes the angular application. This process is called "auto bootstrapping" although we can manually bootstrap angular application.

During the bootstrap process, AngularJS
1. Loads the angular module mentioned within the ng-app directive
2. Creates $injector service responsible for DI in the application.
3. Runs the $compile service.

Typical flow diagram having three directive


1.The compilation Phase:

$compile service looks at the text and attributes of the DOM element. Identifies the directives and embedded expressions. Registers watch for these expressions and updates the UI during angular digest cycle. The compile service compiles the DOM from root element and traverse down the DOM by using depth first traversal algorithm.
During this phase DOM element and its attributes are identified as directive. The directive names are normalized using camleCase. e.g.

  • 1. ng-app is normalized as ngApp,
  • 2. my-custom-directive is normalized as myCustomDirective
  • 3. x-my-custom-directive is normalized as myCustomDirective
  • 4. data-my-custom-directive is normalized as myCustomDirective
  • 5. x: my: custom: directive is normalized as myCustomDirective
  • 6. data:my:custom:directive is normalized as myCustomDirective


':', '-' characters are converted to the camelCase
'data', 'x' are removed from the element and attributes.

Linking phase:

2.  Controller functions: 
After compilation controller and followed by pre-linking function is executed respectively for each directive.
controller facilitates the communication between child and parent directive.  The significance of the controller inside the directive is to
1. modify the $scope of the template and
2 if requested by the child controller, this controller function / object is passed to the child controller and both the controllers can communicate with each other

3. Pre link functions :
After this pre-link function is called. This function can be used manipulate the directive template by appending or prepending.  The pre link function always has the private context with its own directive and can't be accessed by the child controllers.

4. . Post link function ;
Finally post-link function is called for each directive. The order of calling this function is exactly opposite to the compile function. Its starts from the last node and moves up till the root element. In most of the cases we can use this function to apply the CSS to the directive templates.

Typical directive example

customDirective.js having compile function
 

 var app = angular.module("demo",[]);
 app.controller("demoCntrl", function($scope,$q,utilService){
  console.log("inside main controller");
  $scope.tableOptions = {
   headerTemplate: true,
   footerTemplatle: true,
   data : [
    {name:'John'},
    {name:'Varghese'},
    {name:'Mike'}
   ]
  }
 });
 app.directive("myCustomTable", ['$compile','utilService', function($compile,utilService){
   return {
  scope :{
   model:"=",
  },
  transclude : false,
  templateUrl : 'tmpl/tablerow.html',
  compile: function($element, $attributes){
   return {
    pre : function($scope, $element, $attributes, controller, transcludeFn) {
     if($scope.model.headerTemplate !== undefined && $scope.model.headerTemplate === true){
     var template = utilService.getTemplate('tmpl/tableHeader.html');
      var x = $compile(template)($scope);
      $element.prepend(x);
     }
     if($scope.model.footerTemplatle !== undefined && $scope.model.footerTemplatle === true){
      var tmpl = utilService.getTemplate('tmpl/tablefooter.html');
      console.log(tmpl);
      var x = $compile(tmpl)($scope);
      $element.append(x);
     }

    },
    post : function($scope, $element, $attributes, controller, transcludeFn){
     
     $element.addClass(".myCustomTable");
    }
   }
  },
  controller : function($scope,$templateCache,$q,$interpolate){
   if($scope.model.footerTemplatle == undefined ){
    $scope.model.footerTemplatle = false;
   }    
  },
   };
 }])
 .run(['$templateCache',function($templateCache){
 $templateCache.put('tmpl/tablerow.html','
{{record.name}}
'); $templateCache.put('tmpl/tablefooter.html', "showing {{model.data.length}} items" ); $templateCache.put('tmpl/tableHeader.html','Name
'); }]); app.factory('utilService',[ '$templateCache','$interpolate','$q',function($templateCache,$interpolate,$q){ var utilService = {}; utilService.getTemplate = function(templatePath){ var template = $templateCache.get(templatePath); var startSym = $interpolate.startSymbol(), endSym = $interpolate.endSymbol(); if (startSym !== '{{' || endSym !== '}}') { template = template.replace(/\{\{/g, startSym); template = template.replace(/\}\}/g, endSym); } return template; }; return utilService; }]);

5 comments:

  1. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in ANGULAR JS, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on ANGULAR JS. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Nitesh Kumar
    MaxMunus
    E-mail: nitesh@maxmunus.com
    Skype id: nitesh_maxmunus
    Ph:(+91) 8553912023
    http://www.maxmunus.com/




    ReplyDelete
  2. Nice Information
    "Sanjary Academy provides excellent training for Piping design course. Best Piping Design Training Institute in Hyderabad,
    Telangana. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller
    course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course."
    Piping Design Course
    Piping Design Course in India­
    Piping Design Course in Hyderabad
    QA / QC Course
    QA / QC Course in india
    QA / QC Course in Hyderabad
    Document Controller course
    Pressure Vessel Design Course
    Welding Inspector Course
    Quality Management Course
    Quality Management Course in india
    Safety officer course

    ReplyDelete

  3. It is really very helpful for us and I have gathered some important information from this blog.
    Angularjs Development Company – Nintriva
    in India

    ReplyDelete