AngularJS Tutorial

Define AngularJS

Download AngularJS

AngularJS Expression

AngularJS vs Javascript

AngularJS Directives

AngularJS Module

AngularJS Controller

Custom Directive

AngularJS Scope

AngularJS Validation

AngularJS Filter

AngularJS SelectBox

AngularJS Directive

AngularJS Services

AngularJS Directives

AngularJS Routing

Interview Questions

AngularJS Custom Directive

Create New Directives

In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the .directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive. When naming a directive, you must use a camel casing like userFirstName, but when invoking it, you must use '-' separated name like user-First-Name.

You can invoke a directive by using:

  • Element name
  • <body ng-app="myApp">
    
    <my-directive></my-directive>
    
    <script>
    var app = angular.module("myApp", []);
    app.directive("myDirective", function() {
        return {
            template : "Text displayed using my directive element name."
        };
    });
    </script>
    
    </body>

  • Attribute
  • <body>
    
    <div ng-app="myApp" my-directive></div>
    
    <script>
    var app = angular.module("myApp", []);
    app.directive("myDirective", function() {
        return {
            template : "Text Displayed using my directive attribute."
        };
    });
    </script>
    
    </body>

  • Class
  • <body ng-app="myApp">
    
    <div class="my-directive"></div>
    
    <script>
    var app = angular.module("myApp", []);
    app.directive("myDirective", function() {
        return {
    		restrict : "C",
            template : "<b>Text displayed using my directive class name.</b>"
        };
    });
    </script>
    
    </body>

  • Comment
  • <body ng-app="myApp">
    
    <!-- directive: my-directive -->
    
    <script>
    var app = angular.module("myApp", []);
    app.directive("myDirective", function() {
        return {
    		restrict : "M",
    		replace : true,
            template : "<b>Text displayed using my directive in a comment.</b>"
        };
    });
    </script>
    
    </body>

    The legal restrict values are:

  • E for Element name
  • A for Attribute
  • C for Class
  • M for Comment
  • By default the value is EA, meaning that both Element names and attribute names can invoke the directive.