Create Custom Directives in AngularJS

Last Reply 2 months ago By dharmendr

Posted 2 months ago

How to create custom directive in AngularJS and call it on page.

Posted 2 months ago Modified on 2 months ago

Hi rani,

Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using directive function.

A custom directive simply replaces the element for which it is activated.

AngularJS provides support to create custom directives for following type of elements.

  • Element directives : Directive activates when a matching element is encountered.
  • Attribute : Directive activates when a matching attribute is encountered.
  • CSS : Directive activates when a matching css style is encountered.
  • Comment : Directive activates when a matching comment is encountered.

For more details refer below links.

AngularJS Custom Directives

HTML

MyHTML.htm

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <table class="table table-responsive">
        <tr><th>Id</th><th>Name</th><th>Country</th></tr>
        <tr><td>1</td><td>John Hammond</td><td>United States</td></tr>
        <tr><td>2</td><td>Mudassar Khan</td><td>India</td></tr>
        <tr><td>3</td><td>Suzanne Mathews</td><td>France</td></tr>
        <tr><td>4</td><td>Robert Schidner</td><td>Russia</td></tr>
    </table>
</body>
</html>

Default.htm

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.directive('myTable', function () {
            var obj = {
                restrict: 'A',
                template: '<table class="table table-responsive">' +
                          '<tr><th>Id</th><th>Name</th><th>Country</th></tr>' +
                          '<tr><td>1</td><td>John Hammond</td><td>United States</td></tr>' +
                          '<tr><td>2</td><td>Mudassar Khan</td><td>India</td></tr>' +
                          '<tr><td>3</td><td>Suzanne Mathews</td><td>France</td></tr>' +
                          '<tr><td>4</td><td>Robert Schidner</td><td>Russia</td></tr>' +
                          '</table>'
            }

            return obj;
        });

        app.directive('myHtml', function () {
            var obj = {
                restrict: 'E',
                templateUrl: 'MyHTML.htm'
            }

            return obj;
        }); 
    </script>
</head>
<body>
    <div ng-app="MyApp">
        <h3>Attribute directives</h3>
        <div my-table>
        </div>
        <h3>Element directives</h3>
        <my-html />
    </div>
</body>
</html>

Screenshot