Directives In AngularJS

In this article, you will learn how to create directives in AngularJS application. This post helping us to learn how to create directives in AngularJS application, type of directive, scope of directive, etc.

Introduction


Directives are one of the most important component of AngularJS application. They are extended HTML attributes. In other words, directives are something that introduces new syntax. They are markers on the DOM element which provides some special behavior to DOM elements and tell AngularJS's HTML compiler to attach.

Their are many built-in directives such as ng-model, ng-repeat, ng-show, ng-bind etc. All these directives provide special behavior to DOM elements. For example, ng-show directive conditionally shows an element, ng-click directive adds click events to the element; ng-app directive initializes an AngularJS application, etc.

Custom directives


Custom directives are used to extend the functionality of HTML. They are defined by using "app.directive()" function in AngularJS. Custom directives replace the element for which they are active. Using "compile" method, AngularJS application finds the matching element and replace with directive definition. This is one time activity HTML compile and load.

Types of Directives


Type of directive determines how they are used. We can implement directives by the following ways:

  • Attribute directives: Directive is active when matching attribute is found.
    1. <input type="text" numeric />  
  • Element directives: Directive is active when matching element is found.
    1. <numeric-Textbox id = "txtAge" />  
  • Component directives: Directive is active when matching component is found.
    1. <!-- directive: numeric-Textbox exp -->  
  • CSS class directives: Directive is active when matching CSS style is found.
    1. <input type="text" class=" numeric "/>  

Directives are registered same way as controller and directive returns a simple object that has many properties to configure the directives. "AngularJS application name.directive" function is used to register a new directive in our module. The first argument to this function is the name of directive and second argument to this function is function that returns a directive definition object. If the directive has any external dependencies such as services, $scope object, etc can be injected in this function.

Hello World Example

The example directive shows static text. The following code shows Hello World directive.

  1. app.directive('helloWorld'function () {  
  2.    return {  
  3.       template: '<h3>Hello World!!</h3>'  
  4.    };  
  5. });  
This directive can be used in HTML as in the following way:

As element:
  1. <hello-world/>  
As attribute
  1. <div hello-world></div>  
If we want to be HTML5 compliant, we can use x- or data- as prefix. The following markup will match hello world directive.
  1. <div data-hello-world></div>  
run output

The following are the important properties of directive:
  • restrict: This property provides way to specify how the directive should use in HTML. In preceding section we saw the directive is defined in the following four ways.

    The restrict option could be set to:

    • 'A' - Only matches attribute name
    • 'E' - Only matches element name
    • 'C' - Only matches class name

  • Template and templateUrl: It specifies the HTML markup that will be generated when the directive is compiled and linked. The template can be complex and can contain other directives, expression, etc. We can also put this HTML markup in separate HTML file and linked-up by using templateUrl property of directive.

  • replace: It is used to specify whether generated template will replace the HTML element on which this directive is attached. It is a Boolean type. When it is set to true the HTML compilation directive is replaced with final output of directive.

  • Controller: Used to define the controller which can be associated with the directive.

  • Link: In AngularJS, directive generate meaningless template unless it is compiled against the right scope. By default directive does not get the new scope (child scope), rather it gets parent scope i.e. if directives used inside the controller, they are used in controller scope. Using link function, we can utilize the scope.

    Link function takes the following three arguments:

    • scope: Scope passed to the directive.
    • elem: Element on which the directive is applied.
    • attrs: Normalized attributes attached to the element on which the directive is applied.

      Link function is primarily used to attach event listeners to the DOM elements, updates the DOM element, watching the model properties changes.

  • Compile: This function is used to perform any DOM transformation before the link function is executing. It takes the following two arguments:

    • tElement: Element on which directive is applied
    • attrs: list of attributes defined

    This function does not have access of scope object.

  • scope: By default directive use the parent scope but this is not required in all the cases. We can define scope that is limited to directive only. This new scope is isolated from the parent scope. The reasons of defining isolated scope are: If we exposed the parent scope, directives are free to modify the properties of scope. In some of the case, directives required several scope properties which is used internally by directive but does not required in parent scope.

    So, we have two type scopes that can be used.

    • Isolated scope: It is a new scope which is not inherited from the parent. Isolating scope, it does not mean that we cannot access the parent scope properties. There are many techniques that allow us to access these and also watch for changes.

    • Child Scope: This is scope which inherits the parent scope.

Child Scope in directive example


The following is the child scope example with directive. Here scope property of the directive is set to true, so directive will use the parent scope.

    Directive code:

    1. app.directive('helloUser'function () {  
    2.    return {  
    3.       scope: true,  
    4.       template: '<h3>Hello {{Myname}}!! </h3>'  
    5.    };  
    6. });  
    HTML implementation
    1. <div ng-controller="demoController">  
    2.    <b>Directive with Parent's scope example</b>  
    3.    <br />  
    4.    <br />  
    5.       Enter Your Name: <input type="text" ng-model="Myname" />  
    6.    <hello-user />  
    7. </div>  
    Controller Code:
    1. app.controller("demoController"function ($scope) {  
    2.    $scope.Myname = "Jignesh";  
    3. });  
    Output:

    result       

Isolated Scope in directive example


The following is isolated scope example with directive. Here scope property of the directive contains the scope variable name and value with prefix. From the prefix AngularJS decides, from where value can be found. Normally the following three prefixes are used in directive:
  • "@" uses to read the attribute value.
  • "=" provides two-way binding.
  • "&" works with functions.
Directive code:
  1. app.directive('helloIsolatedScope'function () {  
  2.    return {  
  3.       scope: {  
  4.          testName: "=name"  
  5.       },  
  6.       template: '<h3>Hello {{testName}}!! </h3>'  
  7.    };  
  8. });  
HTML implementation
  1. <div ng-controller="demoController">  
  2.    <b>Directive with Isolated Scope example</b>  
  3.    <hello-isolated-scope name="Test" />  
  4. </div>  
Controller Code:
  1. app.controller("demoController"function ($scope) {  
  2.    $scope.Myname = "Jignesh";  
  3.    $scope.Test = "Jignesh Trivedi";  
  4. });  
output

Code relation diagram:

Code relation diagram

Summary


This post is helping us to learn how to create directives in AngularJS application, type of directive, scope of directive, etc. Directives are really great feature of AngularJS and it is able to extend our HTML and we can reuse our HTML with the help of directive.