---
title: "How to create Custom directives in AngularJS"  
description: "Custom directives are a key feature in AngularJS for building modular, maintainable applications with enhanced functionality and improved code organiz"  
author: "Ashutosh Patel"  
published: 2024-06-24  
updated: 2024-06-24  
canonical: https://www.mindstick.com/articles/336208/how-to-create-custom-directives-in-angularjs  
category: "angular js"  
tags: ["javascript", "angular js", "angularjs directive"]  
reading_time: 4 minutes  

---

# How to create Custom directives in AngularJS

#### AngularJS Custom Directive

Custom [directives](https://www.mindstick.com/interview/33915/what-are-directives-in-angularjs) 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](https://www.mindstick.com/forum/157881/how-do-you-create-custom-directives-in-angularjs) 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,

```javascript
// 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](https://www.mindstick.com/forum/23337/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) ​​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](https://www.mindstick.com/forum/159117/how-do-you-handle-events-using-jquery-and-attach-event-listeners-to-elements), 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:

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

#### Benefits of Custom Directives

**Reusability-** Add complex behavior or UI components for reuse in [your application](https://answers.mindstick.com/qa/97584/how-do-you-choose-the-correct-camera-for-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](https://answers.mindstick.com/qa/116245/how-does-angularjs-handle-form-validation)-** Create [custom validation](https://www.mindstick.com/forum/1973/custom-validation-attribute) behavior or error messages.

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

**[Data visualization](https://yourviews.mindstick.com/view/85951/how-data-visualization-is-transforming-business-intelligence)-** Use custom charts or graphs.

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

## Example-

```html
<!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

```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](https://www.mindstick.com/mindstickarticle/bdf9e711-e1cb-442d-a090-26807f108da7/images/b693e33e-b5b9-46ee-90f9-d06486b8bedf.png)

Custom directives are key in AngularJS for building modular, maintainable applications with improved functionality and improved [code organization](https://answers.mindstick.com/qa/114028/how-does-object-oriented-programming-improve-code-organization-in-modern-programming-languages). 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](https://www.mindstick.com/articles/336207/single-page-application-in-angularjs)

---

Original Source: https://www.mindstick.com/articles/336208/how-to-create-custom-directives-in-angularjs

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
