AngularJS is a powerful JavaScript framework developed by Google that allows developers to build dynamic and single-page applications efficiently. One of its most powerful features is directives, which extend the functionality of HTML. Directives in AngularJS enable developers to create reusable components, manipulate the DOM, and introduce custom behavior in applications.
Among various types of directives in AngularJS, custom directives are particularly useful because they allow developers to encapsulate logic and UI elements into reusable components.
In this guide, we will explore custom directives in AngularJS step by step, with practical examples to ensure a clear understanding.
1. What Are Directives in AngularJS?
Directives in AngularJS are special markers (attributes, classes, or comments) that tell AngularJS to attach specific behavior to a DOM element. There are built-in directives such as ng-model
, ng-repeat
, and ng-click
. However, AngularJS also allows developers to create custom directives to implement specific functionality.
Types of Directives in AngularJS
- Element directives (
E
) – Applied as a custom HTML tag. - Attribute directives (
A
) – Applied as an attribute of an element. - Class directives (
C
) – Applied as a CSS class. - Comment directives (
M
) – Applied within comments.
Custom directives are mostly used as Element and Attribute directives.
2. Why Use Custom Directives?
Custom directives are useful because they:
✔ Encapsulate Reusable Code – They allow developers to create reusable UI components.
✔ Improve Maintainability – Code is modular and easier to debug.
✔ Enhance Readability – Makes the HTML structure cleaner.
✔ Manipulate the DOM – Allows customization of how elements behave.
3. Creating a Simple Custom Directive in AngularJS
Let’s start by creating a simple AngularJS application with a custom directive.
Step 1: Setup AngularJS
First, include AngularJS in your HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Custom Directive</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MainController">
<custom-directive></custom-directive>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("MainController", function ($scope) {
$scope.message = "Hello from Controller!";
});
app.directive("customDirective", function () {
return {
restrict: "E",
template: "<h1>This is a Custom Directive!</h1>"
};
});
</script>
</body>
</html>
Explanation:
ng-app="myApp"
– Defines the AngularJS application.ng-controller="MainController"
– Defines a controller managing the scope.directive("customDirective", function() {...}
– Creates a custom directive.restrict: "E"
– Makes it an element directive (<custom-directive>
).template
– Defines the HTML content that will be rendered.
4. Understanding Directive Restrictions
Directives can be applied in different ways using the restrict property.
Restrict Type | Usage | Example |
---|---|---|
E (Element) | As an HTML tag | <my-directive></my-directive> |
A (Attribute) | As an HTML attribute | <div my-directive></div> |
C (Class) | As a CSS class | <div class="my-directive"></div> |
M (Comment) | As a comment | <!-- directive: my-directive --> |
Example of an Attribute Directive (A
)
<div my-directive></div>
app.directive("myDirective", function () {
return {
restrict: "A",
template: "<p>This is an Attribute Directive</p>"
};
});
5. Using Scope in Directives
Directives can have their own scope, which is useful when passing data.
Isolated Scope Example
<div my-directive message="customMessage"></div>
app.controller("MainController", function ($scope) {
$scope.customMessage = "Hello from Scope!";
});
app.directive("myDirective", function () {
return {
restrict: "A",
scope: {
message: "@"
},
template: "<p>Message: {{ message }}</p>"
};
});
Explanation:
✔ The scope: { message: “@” } binds an attribute value (customMessage
) to the directive.
6. Using the Link Function
The link function allows us to manipulate the DOM dynamically.
app.directive("myDirective", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.css("color", "blue");
}
};
});
Here, the text color of the element will be set to blue.
7. Using the Controller in Directives
Directives can have their own controllers to handle business logic.
app.directive("myDirective", function () {
return {
restrict: "E",
template: "<button ng-click='clickMe()'>Click Me</button>",
controller: function ($scope) {
$scope.clickMe = function () {
alert("Button Clicked!");
};
}
};
});
8. Using Templates and Template URLs
Templates define the HTML structure of directives.
✔ Using template
Inline
app.directive("myDirective", function () {
return {
restrict: "E",
template: "<h2>Inline Template Example</h2>"
};
});
✔ Using templateUrl
for External Files
app.directive("myDirective", function () {
return {
restrict: "E",
templateUrl: "template.html"
};
});
The template.html
file contains:
<h2>This is an External Template Example</h2>
9. Communicating Between Directives and Controllers
Directives can communicate with controllers using:
- Isolated scope (
@
,=
,&
) - Broadcasting events
Example using &
:
app.directive("myDirective", function () {
return {
restrict: "E",
scope: {
action: "&"
},
template: "<button ng-click='action()'>Call Parent Function</button>"
};
});
<my-directive action="showAlert()"></my-directive>
$scope.showAlert = function () {
alert("Alert from Parent Controller!");
};