articles

Home / DeveloperSection / Articles / How to create Custom directives in AngularJS

How to create Custom directives in AngularJS

How to create Custom directives in AngularJS

Ashutosh Kumar Verma 254 24-Jun-2024

AngularJS Custom Directive

Custom directives in AngularJS can extend the functionality of HTML by creating reusable objects or actions. They are a powerful feature with robust DOM transformation, provide reusable UI components, and improve code design. Here is an explanation of how custom directives work in AngularJS:

Basics of Custom Directives


Direction Definition Object (DDO)

A method is defined by a directive definition object (DDO), which specifies how the directive should behave, what parameters or functions it should use, and how it should interact with the DOM.


Directive Types

  • Element assignments- Create a new HTML element.
  • Attribute directives Change the behavior or appearance of existing features.
  • Class directives- Apply characters or strategies to objects based on their learning.
  • Comment directives- Restrict directives to HTML text.

 

Structure of a Custom Directive

Here is a prime example of traditional teaching,

// Example: Custom directive 'myDirective'
app.directive('myDirective', function() {
 return {
   restrict: 'E', // Restrict usage to elements
   template: '<div>{{ message }}</div>', // Inline template
   scope: {
     message: '@' // One-way binding (string)
   },
   link: function(scope, element, attrs) {
     // Link function: DOM manipulation and behavior
     element.on('click', function() {
       element.css('background-color', 'yellow');
     });
   }
 };
});

 

Description of Directory Definition Object (DDO)


restrict-Specifies how the directive can be used. Possible values ​​are:

  • ‘E’- element directions (<my-direction></my-direction>).
  • ‘a’- attribute directions (<div my-direction></div>).
  • ‘c’- class direction (<div class="my-direction"></div>).
  • ‘m’- instruction directive (<!-- directive my-directive -->).

template or templateUrl- Defines the appearance/design of the guide. It can be an inline HTML (template) or a URL in an external file (templateUrl).

scope- Defines the isolated scope of the doctrine. This determines the behavior of the binding data of the instruction. The most common options are:

  • @- One-way binding (string).
  • =- bilateral relation (object).
  • &- binding function (words).

‘Link’ function- Each directive is executed once per instance. This allows you to manipulate the DOM, add event listeners, interact with controllers, and perform other directive-specific operations.

 

Using the Custom Directive

Once defined, you can use the custom directives in your HTML just like any embedded AngularJS directive:

<my-directive message="Hello from directive"></my-directive>

 

Benefits of Custom Directives

Reusability- Add complex behavior or UI components for reuse in your application.

Separation of concerns- DOM promotes clean code by separating variables and business logic.

Improved readability- Increases readability and maintainability by squeezing complex HTML and JavaScript interfaces into reusable objects.

 

Application of the model

Form Validation- Create custom validation behavior or error messages.

UI components- Create reusable elements such as modals, tooltips, or sliders.

Data visualization- Use custom charts or graphs.

Event handling- Associate specific behavior with DOM events in a reusable way.

Example- 

<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body data-ng-controller ="myController">
   
<div class="container my-4">
    <!-- first way to load the custome file in your custome directive as attribute -->
    <div my-directive></div>
    <hr>
   
    <!-- other way to load custome file in your custome derective as element -->
    <my-directive text-color="blue"></my-directive>
</div>

<script>
    angular.module('myApp', [])
        .controller('myController', ['$scope', function($scope){
            $scope.name = "This is Custom Directive file message";
        }])
        .directive('myDirective', function(){
            return {
                // Custom file location with file name
                templateUrl: "Custome-file.html",
                link: function(scope, element, attrs){
                   
                    // apply the css on custome file attributes                                        
                    var textColor = attrs.textColor;
                    // Applying CSS properties to the element
                    element.css({                            
                        'color': textColor
                    });

                    // apply mouseover event on customefile elements
                    element.on('mouseover', function(){
                        element.css('background-color', 'yellow');
                       
                    });
                    // apply mouseout event on customefile elements
                    element.on('mouseout', function(){
                        element.css('background-color', 'transparent');                            
                    });                      
                }                                      
            };
        });
</script>
</body>
</html>

Custome-file.html

<div class="row">
   <div class="col-12">
    <!--  -->
    <h3>This is custome file</h3>
    
    <!-- bind the value of $scope.name here -->
    <p data-ng-bind="name"></p>
   </div>
</div>

 

Note above files keep in same folder or directive

Output-

How to create Custom directives in AngularJS

Custom directives are key in AngularJS for building modular, maintainable applications with improved functionality and improved code organization. They empower developers to extend the capabilities of HTML and create more transparent, reusable features and actions in their applications.

 

Also, Read: Single Page Application in AngularJS


Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By