AngularJS Custom Directives

Angularjs is an open source Javascript Framework sponsored by Google. Angularjs is not a traditional way of MVC framework, it is nearly to MV*(Model-view-whatever) or MVVM (Model-view-viewmodel). It helps to create Single Page Applications (SPAs) with appropriate resources like css, html, js etc are dynamically updated in response to user actions without page reload. It allows to build well organized app with distinguished features, easily testable and maintainable web application.

What is Directives?

Directives are differentiating feature of angularjs that brings additional functionality to HTML. It is one of the core and central aspect of AngularJS to define powerful template. It allow us to extend the vocabulary of HTML in directive fashion. It extends HTML either by new elements or  new attributes to existing elements or expressions. We can define our own custom directives that are reusable components as our needs and to manipulate DOM elements.

Built-in directives

There are some built-in directives in Angularjs such as  ng-app, ng-controller, ng-model, ng-repeat etc. ng is the prefix of all angular built-in directives. The roles of this directives are described below :

ng-app : To initialize the app
ng-controller : To initialize the controller
ng-model : Bind the html elements like input, select etc to model.

Example:

It's a baby girl !

Custom Directives

1. Create a directive
Directive can be registered with angular module. For example:

var app = angular.module('demoModule');
app.directive('sample', function () {
return {
restrict : 'E',
   template: 'My first directive'
   };
});
  • On the above line of code, you can see that to call a directive() function on module. A new directive is registered once you call this function.
  • First parameter is the name of directive that we use in the HTML template when we need to activate this directive.
  • Second parameter is a factory function that return directive’s definition when invoked.
  • The above factory function have two properties template and restrict. Invoke directive eg: <sample></sample>. The above element would replaced with template content defined in the directive.

    2. Types of directives
    There are four different ways to implement custom directives in angularjs. They are listed below with additional info on how to activate these type of directives in template.

    Element directives
    The element directive is enabled when app finds a matching HTML element in the HTML template.

     
    

    Attribute directives
    The attribute directive is enabled when app finds a matching HTML attribute in the template.

    CSS Class directives
    The directive is enabled when app finds a matching CSS Class.

    Comment directives
    The directive is activated when AngularJS finds a matching HTML comment.

    
    

    The element and attribute are most commonly used  directives.

    Example:

    app.directive('sample', function () {
        return {
    	restrict : 'EA',
            	template: '
    
    {{myval}}
    }; });

    3. Properties of directives
    There are some predefined list of properties that can be used in the custom directives. Each of them have separate responsibilities which return a directive definition object.  To get the complete list of properties, please refer  https://docs.angularjs.org/api/ng/service/$compile.  Some of commonly used properties are described below:

      restrict

    To specify how a directive is implemented in angular app. There are 4 restrict options, they are:

    restrict : 'A'   --> attribute (default one) | 
    restrict : 'E' --> element | restrict : 'C' --> Class |
    restrict : 'M' --> Comment |

    Also specify the multiple restrict option to support more than one element method, both element and attribute method.

    restrict : ‘EA’

    scope
    To accessing data or methods inside template and link function. By default, the directives do not create their own scope without explicitly set. Different types of scopes are able to define, they are:

    scope : false –> uses its parent scope (that is scope from controller)
    scope : true –> gets new scope
    scope : {} –> gets new isolated scope that doesn’t inherit from parent and exists on its own

    template
    To specify the HTML content that will be produced when directive is compiled

    templateUrl
    To specify the path of template that should be used by directives

    Example:

    app.directive('sample', function () {
        return {
            restrict: 'E', //E = element, A = attribute, C = class, M = comment         
            scope: false,        
            templateUrl: 'sample.tpl.html'        
        }
    });

    4. Functions of directives
    There are four functions that are executed to create directive and applied to explore the DOM. Before the page is rendered and DOM gets ready, the Angularjs process these functions. All these functions are not needed commonly. They are described below.

    Compile
    To manipulate DOM before it is compiled and linked by allowing it to add/change directives and add/change other DOM elements. It is invoked once each occurance of directive in the HTML page. It only needs one-time configuration of element containing directive.

    Controller
    To facilitates directive communication. Sibling and child directives can request the controller of their siblings and parents to communicate information.

    Pre-link
    To  allow for private $scope manipulation before the post-link process begins.

    Post-link
    It is the primary method of the directive. It is normally used as link functions.

    Example:

    app.directive("sample",function () {
        return {
          controller: function() {
    	....
          },
          link: function() { // post link
          	....
          }
        }
      });

    5. Compile Directives
    While executing the application,  Angular starts parsing the DOM using the $compile service. This service is looking for directives in the HTML markup and matches them across registered directives. Once all the directives have been identified, Angular executes their compile functions. The compile function returns a link function which is added to the list of link functions to be executed later. This is called the compile phase. If a directive needs to be cloned multiple times using ng-repeat, we get a performance benefit as the compile function runs once for the cloned template, but the link function runs for each cloned instance. That’s why the compile function does not receive a scope.

    After the compile phase is over the linking phase, where the collected link functions are executed, one by one starts. The templates produced by the directives are evaluated against correct scope and are turned into live DOM which react to events.

    Angularjs start processing the DOM when it found out the ng-app attribute defined. If the ng-app attribute is set on html tag, it starts processing from html tag onwards which is assumed as the starting point. It recursively investigates all the child elements based on its pattern that corresponds to the directives which is already defined in our angular application.

    Wrapping up
    The blog describes  fundamentals of angularjs directives, even though it does not cater a detailed insight to its features. Hope, the post was really helpful in enlightening of Angularjs directive basic and how it works. You can always think outside the box to create your own custom directives and do some awesome Angular stuffs.

    Know More About This Topic from our Techies

    Latest Post