How to Create a Custom Directive in AngularJS: Key Steps, Concepts, Practical Examples, and More
By Rohan Vats
Updated on Dec 31, 2024 | 22 min read | 6.4k views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Dec 31, 2024 | 22 min read | 6.4k views
Share:
Table of Contents
Have you ever hit a roadblock where prebuilt AngularJS directives just don’t meet your project’s unique requirements? As a developer, you know that sticking to cookie-cutter solutions can limit your application’s potential. This is where custom directives in AngularJS come into play.
Custom directives let you expand HTML’s capabilities, creating tailored elements and behaviors that fit your exact needs. Whether you’re streamlining a complex workflow or adding reusable components, mastering how to create custom directive in Angular can transform your development process.
In this blog, you’ll walk you through the steps to build custom directives, break down the concepts, and share practical examples. Get ready to elevate your AngularJS projects with this essential skill!
A custom directive in AngularJS extends HTML by creating reusable components that add custom behavior to elements. These directives transform standard HTML tags into dynamic, interactive components that can be reused throughout your application.
Let’s explore best practices for creating effective custom directives.
A built-in directive like ng-model binds an input element to a property in the AngularJS controller. While useful, custom directives offer greater flexibility by allowing you to create custom HTML tags or attributes with reusable functionality.
For example, a custom directive could handle a date picker, encapsulating all the logic for displaying a calendar, so you don’t need to rewrite the same logic each time.
Boost your web development career – Learn AngularJS and build dynamic applications with upGrad’s in-depth software engineering courses. Start developing your skills today!
Now, let's explore why custom directives are essential in 2025 and how they benefit modern web development.
Custom directives offer several key advantages, making them essential for modern AngularJS development. Some of the major benefits of custom directives are as follows:
Scenarios Where Custom Directives are Better Than Built-In Options
Role in Creating Dynamic Web Applications
Custom directives are essential for building dynamic web applications. They allow you to create custom HTML elements that can update in real-time based on your app's state.
By understanding how to create custom directive in Angular, you ensure that your app remains interactive and responsive. These elements can change their behavior and appearance as needed, providing a seamless user experience.
Also Read: Best Web Development Project Ideas for Beginners & Final Year Students in 2025
Let’s now see how to register a module in AngularJS.
To use a custom directive in AngularJS, you must first register it within an AngularJS module. This involves defining the directive and telling AngularJS how to handle it. Here is how to do it:
Syntax:
angular.module('app').directive('directiveName', function() {
return {
restrict: 'E', // restrict to an element
template: '<div>Custom directive content</div>'
};
});
Example of Using restrict and template
Here’s an example where the custom directive replaces a div element with some new content.
angular.module('app').directive('greetingDirective', function() {
return {
restrict: 'E', // This directive is an element
template: '<h1>Hello, welcome to AngularJS!</h1>'
};
});
Output
When you add the following HTML to your AngularJS application:
<greeting-directive></greeting-directive>
The directive replaces the element with its content:
<h1>Hello, welcome to AngularJS!</h1>
This demonstrates how AngularJS activates a directive based on matching an HTML element, simplifying code and enhancing functionality.
Now, let’s dive into the key concepts behind creating custom directives in AngularJS and understand the building blocks essential for their functionality.
Creating custom directives in AngularJS requires you to understand key concepts that define their functionality. These include defining directives, managing scope, and using data binding to connect your component with the rest of the app.
Learning how to create custom directive in Angular enables you to extend HTML’s capabilities and build powerful, reusable components.
In this section, you’ll explore the fundamental building blocks of directives and gain the skills to create efficient components.
This function allows AngularJS to link the directive’s functionality to a specific part of your application, ensuring proper interaction with the model.
Let’s have a look at the parameters in a quick, tabular form:
Parameter |
Description |
restrict | Specifies how the directive can be used (element, attribute, class, or comment). |
template | Defines the HTML content rendered when the directive is used. |
scope | Defines an isolated scope for the directive, preventing interference with the outer scope. |
link | The function used to add custom behavior, manipulate DOM elements, and set up event handlers. |
Also Read: Top 25+ HTML Project Ideas for Beginners in 2025: Source Code, Career Insights, and More
Now, let’s explore how event handling in custom directives allows you to manage user interactions and enhance your application’s functionality.
Event handling is crucial when you work with custom directives in AngularJS. It allows you to manage user interactions, like clicks and hovers, directly within your components.
In this section, you’ll learn how to handle events within your directives. We’ll also cover how the link function helps set up event listeners and manage interactions.
Example Implementation with Real-World Use Case:
Here’s an example of handling a click event within a custom directive to toggle visibility:
angular.module('app').directive('toggleVisibility', function() {
return {
restrict: 'E',
scope: {},
template: '<button>Toggle</button><div class="content">Content to toggle</div>',
link: function(scope, element, attrs) {
var button = element.find('button');
var content = element.find('div');
button.on('click', function() {
content.toggle(); // Toggles the visibility of the content
});
}
};
});
In this example:
This demonstrates how custom directives in AngularJS can handle user interactions effectively, providing powerful behavior for web applications.
Also Read: AngularJS for Web Development: Top 10 Compelling Reasons
Now, let’s dive into the different types of AngularJS directives and understand how each plays a unique role in enhancing your web applications.
In AngularJS, directives are classified into four main types. Each type serves a different purpose, extending the capabilities of HTML in unique ways. Understanding these types is crucial when learning how to create custom directive in Angular.
Let’s explore each directive type with examples and explanations.
Element directives are used as custom HTML elements. They are the most common type of directive in AngularJS and allow you to extend HTML with new elements.
How it works:
You create a new HTML element that behaves like a regular HTML tag but with custom behavior defined by the directive.
Example:
angular.module('app').directive('myElement', function() {
return {
restrict: 'E', // Restrict to an element
template: '<div>Custom Element Content</div>'
};
});
In this example, <my-element></my-element> becomes a custom tag in your HTML, rendered by AngularJS according to the template.
Attribute directives are used to add custom behavior to existing elements, often by modifying the DOM element or its attributes.
How it works:
Attribute directives modify the appearance or behavior of an element they are applied to without changing the element's structure.
Example:
angular.module('app').directive('myAttribute', function() {
return {
restrict: 'A', // Restrict to an attribute
link: function(scope, element, attrs) {
element.css('color', 'blue'); // Changes the text color to blue
}
};
});
In this case, <div my-attribute></div> will apply the directive to change the text color of the div element.
CSS class directives apply custom behavior to elements based on their class. These are used when you want to control CSS, i.e., specific styles or behaviors associated with particular classes.
How it works:
You define a directive that targets elements with a specific class, making it easy to reuse across multiple elements.
Example:
angular.module('app').directive('myClass', function() {
return {
restrict: 'C', // Restrict to a CSS class
link: function(scope, element, attrs) {
element.css('background-color', 'yellow'); // Changes background color to yellow
}
};
});
This directive will apply the background color change to any element with the my-class class.
Comment directives are used for embedding custom behaviors within comments in HTML. These directives are less common but can be useful for testing or dynamically creating elements.
How it works:
The directive is applied within an HTML comment, allowing AngularJS to process the content and add behavior dynamically.
Example:
angular.module('app').directive('myComment', function() {
return {
restrict: 'M', // Restrict to a comment
template: '<div>Content Generated by Comment Directive</div>'
};
});
This directive will allow you to add behavior or templates inside comments like this:
<!-- my-comment -->, and AngularJS will replace it with the directive's content.
If you're creating a custom directive in AngularJS or learning how to create custom directive in Angular, understanding these four types helps you use AngularJS to its full potential.
Also Read: Web Application Architecture: Function, Components, Types & Real Life Examples
Now, let’s dive into how to create a custom directive in Angular, with a detailed breakdown of the key steps and concepts involved.
Creating a custom directive in Angular lets you extend HTML’s functionality by adding dynamic, reusable elements to your application. In this section, you’ll learn how to define a directive using the @Directive decorator and how to apply it in your HTML.
You’ll also explore key concepts like decorators, dependency injection, and registering your directive with an Angular module. This will give you the tools to create efficient, modular components for your projects.
The first step in creating a custom directive in Angular is defining it using the @Directive decorator, which tells Angular that the class is a directive.
How to do it:
Use the @Directive decorator to define a class, specifying the selector and other properties.
import { Directive } from '@angular/core';
@Directive({
selector: '[ngGuru]' // Defines how the directive will be used in HTML
})
export class NgGuruDirective {
constructor() {
console.log('NgGuru directive applied!');
}
}
Why it matters:
The @Directive decorator allows Angular to recognize and process the class as a directive. The selector defines how the directive will be applied in your HTML.
To make your directive interact with the DOM, you inject services like Renderer2 and ElementRef. These services help manipulate DOM elements safely and efficiently.
How to do it:
Inject Renderer2 to change DOM properties and ElementRef to access the native DOM element.
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[ngGuru]'
})
export class NgGuruDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'color', 'blue'); // Change text color to blue
}
}
Why it matters:
Renderer2 allows you to safely modify the DOM, and ElementRef gives you direct access to the DOM element, enabling dynamic changes like applying styles.
After creating your directive, you need to register it with an Angular module to make it available for use throughout your application.
How to do it:
Add your directive to the declarations array of your Angular module.
import { NgGuruDirective } from './ng-guru.directive';
@NgModule({
declarations: [NgGuruDirective],
exports: [NgGuruDirective]
})
export class AppModule {}
Why it matters:
Registering the directive with the module ensures Angular can find and apply it wherever it’s used in the application.
Once your directive is defined and registered, you can apply it to elements in your HTML.
How to do it:
In your HTML, use the selector defined in the directive to apply it to an element.
<div ngGuru>This text will be blue.</div>
Why it matters:
By applying the directive as an attribute, Angular processes the element according to the behavior defined in your custom directive.
Here are a few major points to remember:
Use descriptive names for your directives, typically in camelCase for class names (e.g., appCustomDirective) and kebab-case for HTML elements (e.g., <app-custom-directive>).
Choose a meaningful selector type: element, attribute, class, or comment, based on how you want the directive to be applied in HTML.
Decide whether your directive needs an isolated scope (to prevent it from affecting other parts of the app) or can inherit scope from the parent controller.
For small templates, define them directly within the directive. For larger templates, use templateUrl to link to an external HTML file for better organization.
The restrict property defines how your directive will be used: E (element), A (attribute), C (class), or M (comment).
Keep your directives lightweight to maintain performance. Avoid unnecessary watchers or event listeners that could degrade the app’s efficiency.
Build directives with reusability in mind, focusing on one task per directive to keep your codebase modular and maintainable.
Document your custom directives clearly so other developers (or future you) can understand how they work and how they should be used.
Example
Here’s an example of a directive that changes the background color of an element:
import { Directive, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[ngBackgroundColor]'
})
export class NgBackgroundColorDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
}
}
You would use it in HTML as follows:
<p ngBackgroundColor>This paragraph has a yellow background.</p>
Output
When applied, the custom directive will change the background color of the paragraph to yellow based on the logic defined in the directive.
Use Cases
Also Read: Difference Between HTML and HTML 5 : Features and Advantages
Now, let’s explore the scope and data binding in AngularJS and understand how they connect your custom directives with the rest of your application.
In AngularJS, the scope links the view (HTML) and the controller (JavaScript). It manages the flow of data between them, ensuring the view updates when the model changes.
Custom directives can access the parent controller’s scope, enabling seamless data manipulation. Understanding how scope works is essential for creating dynamic, responsive applications.
Let’s explore how scope interacts with custom directives.
Example: Using Scope in Custom Directives
Custom directives can inherit or isolate scope from their parent controller. This means directives can either share the controller’s data or have their own isolated scope to protect data.
Isolated Scope:
An isolated scope means the directive has its own scope and does not share data with the parent scope. This is useful when you want to prevent the directive from affecting the parent controller’s data.
angular.module('app').directive('isolatedDirective', function() {
return {
restrict: 'E',
scope: {
message: '@' // Isolated scope, receives data from the attribute
},
template: '<div>{{message}}</div>'
};
});
Inherited Scope:
Inherited scope means the directive inherits the scope from its parent controller, allowing it to access the parent data.
angular.module('app').directive('inheritedDirective', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
console.log(scope.parentData); // Accessing parent controller's data
}
};
});
Importance of the Parent Controller’s Scope:
The parent controller’s scope is crucial when passing data to custom directives, especially when you want the directive to share information with the parent controller. This allows seamless data sharing and manipulation across different components of the application.
Now, let’s dive into data binding in AngularJS and understand how it connects your application’s model and view.
AngularJS provides various types of data binding: @ (one-way binding), = (two-way binding), and & (event binding), each serving different purposes for data flow between the parent scope and directives.
Let’s have a look at these one by one:
1. Interpolation
Interpolation is a type of one-way binding where expressions are inserted into HTML using double curly braces ({{}}).
Example:
<div>{{ user.name }}</div> <!-- Displays user.name dynamically -->
2. Property Binding
This binds the properties of an element to the model’s properties, allowing dynamic setting of element properties.
Example:
<input type="text" ng-model="user.name" /> <!-- Binds input field to model -->
3. Event Binding
Event binding links the view to an event handler in the controller, listening for events like clicks or changes.
Example:
<button ng-click="submitForm()">Submit</button> <!-- Binds click event to controller -->
Two-Way Data Binding
Two-way data binding ensures that changes in the model are immediately reflected in the view, and any updates in the view are reflected in the model.
Example:
<input ng-model="user.name" /> <!-- Automatically updates user.name on input →
These data binding techniques are fundamental to connecting your view and model in AngularJS, allowing you to build dynamic, interactive web applications.
Now, let’s explore practical examples of custom directives in AngularJS and see how they can be used to enhance your web applications.
Custom directives in AngularJS are powerful tools for enhancing your web applications. They allow you to create reusable, modular components that can be applied across various parts of your application.
Below are some practical examples where custom directives are commonly used, demonstrating their versatility in building dynamic and interactive user interfaces.
Use Case |
Description |
Example |
UI Components | Custom directives are perfect for building UI elements like modals, carousels, and tooltips. These components can be reused across the app. | Create a reusable modal directive to show and hide modal content based on user interaction. |
Dynamic Forms | Custom directives allow you to build dynamic forms with features like real-time validation and handling user input. | Use directives to create custom form controls, such as dropdowns or date pickers, with built-in validation. |
Data Visualizations | Directives can be used to render charts, graphs, and other data visualizations that update in real-time. | Build a custom directive to display dynamic, real-time data in a chart, like updating stock prices or sensor readings. |
Now, let's dive into UI components like modals, carousels, and tooltips, and explore their implementation using custom directives.
Custom directives are perfect for creating reusable UI components like modals, carousels, and tooltips. They allow you to manage shared functionality, like showing or hiding content, in a modular way.
Example:
A modal directive can be created to handle the display, hiding, and content swapping of a modal window, ensuring that the logic is reusable across multiple parts of your application.
Next, let’s look at dynamic forms, focusing on validation and handling user input through custom directives.
Another common use case for custom directives in AngularJS is handling dynamic forms. Directives can encapsulate form controls and validation logic, making it easier to manage complex forms.
Example:
A custom directive for a date picker can be created with validation, ensuring the input meets the correct format before submitting the form.
Next, let’s explore data visualizations, including how to create charts and graphs with real-time updates using custom directives.
Custom directives are ideal for creating real-time data visualizations like charts and graphs. With AngularJS’s data-binding, they can automatically update the view when data changes.
Example:
A real-time stock price chart can be built as a custom directive that updates dynamically whenever new data is received, making it ideal for financial applications or live dashboards.
From UI components to dynamic forms and real-time data visualizations, directives play a vital role in building maintainable and scalable AngularJS applications.
Now, let’s look at real-world use cases where custom directives in AngularJS are applied to solve common development challenges.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Custom directives in AngularJS are essential for building modular, reusable components that enhance user experience and application functionality.
Here are a few real-world use cases demonstrating how these directives are applied to solve common development challenges.
Tooltips provide additional information when users hover over an element. A custom tooltip directive in AngularJS allows you to display helpful messages without cluttering the interface.
How it works:
The directive is applied to an element, and when the user hovers over it, the tooltip appears with the specified message.
Code Example:
angular.module('app').directive('tooltip', function() {
return {
restrict: 'A', // Apply as an attribute
link: function(scope, element, attrs) {
var tooltipText = attrs.tooltip; // Get the tooltip message
var tooltipElement = angular.element('<div class="tooltip">' + tooltipText + '</div>');
element.append(tooltipElement);
// Show tooltip on mouseenter
element.on('mouseenter', function() {
tooltipElement.addClass('visible');
});
// Hide tooltip on mouseleave
element.on('mouseleave', function() {
tooltipElement.removeClass('visible');
});
}
};
});
Result:
When added to an HTML element like <div tooltip="This is a tooltip">, the user will see the tooltip text appear when hovering over the element.
Form validation is a crucial part of any web application. A custom form validation directive ensures that user input is validated on the front-end before submitting it to the server.
How it works:
This directive can check the validity of a form input, such as ensuring a valid email format or that a required field is not empty.
Code Example:
angular.module('app').directive('validEmail', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$validators.email = function(modelValue) {
if (modelValue) {
var regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return regex.test(modelValue);
}
return true; // If there's no value, assume it's valid
};
}
};
});
Result:
When applied to an input element like <input type="email" name="email" ng-model="user.email" valid-email>, the directive will validate the email address format, ensuring it matches the regular expression.
Also Read: Angular js vs Angular: Key Differences, Which Framework is Better, Real-world Examples, and More
A custom interactive data table directive allows you to create dynamic tables that support sorting, filtering, and pagination, making it easier to work with large datasets.
How it works:
The directive enables sorting by clicking on column headers, filtering data based on user input, and paging through the results.
Code Example:
angular.module('app').directive('dataTable', function() {
return {
restrict: 'E', // Apply as an element
scope: {
data: '='
},
template: `
<table>
<thead>
<tr>
<th ng-repeat="header in headers" ng-click="sortBy(header)">
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in sortedData">
<td ng-repeat="cell in row">{{ cell }}</td>
</tr>
</tbody>
</table>
`,
link: function(scope) {
scope.headers = Object.keys(scope.data[0]);
scope.sortedData = scope.data;
scope.sortBy = function(header) {
scope.sortedData = scope.sortedData.sort((a, b) => a[header] > b[header] ? 1 : -1);
};
}
};
});
Result:
The directive can be used in HTML like <data-table data="tableData"></data-table>. The table data will be displayed, and clicking on the column headers will sort the rows.
These custom directives in AngularJS provide valuable solutions for building dynamic, reusable components in web applications.
Now, let’s explore best practices for creating effective custom directives to ensure your AngularJS components are efficient and maintainable.
Creating custom directives in AngularJS can greatly enhance your application's modularity and reusability. However, to ensure your directives are efficient, maintainable, and easy to use, it's essential to follow best practices.
Below are some tips to guide you in building effective custom directives.
Example: Instead of naming a directive myDirective, name it customTooltip if it’s for a tooltip component.
Tip: Break down complex functionality into smaller, reusable directives instead of adding too many features to a single one.
Example: Use the link function to add event listeners and remove them in the destroy lifecycle event to prevent memory leaks.
Tip: Use unit tests and end-to-end tests to validate that your directives perform well and interact properly with the rest of the application.
By following these best practices, you can create custom directives in AngularJS that are efficient, maintainable, and easy to use in your web applications.
Now, let’s see how upGrad can help you master AngularJS and enhance your skills in building custom directives.
upGrad is a leading platform dedicated to helping professionals and students elevate their web development skills. Whether you’re mastering AngularJS or expanding your expertise in full-stack development, upGrad offers practical, hands-on learning experiences guided by industry experts.
With real-world projects and personalized support, you’ll gain the skills needed to build dynamic and efficient applications. Explore a variety of courses designed to strengthen your knowledge and advance your career in software development:
Get personalized guidance from upGrad’s experts or visit your nearest upGrad Career Centre to fast-track your learning journey and achieve your career goals!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Reference Link:
https://blog.angular.dev/angular-developer-survey-2023-86372317c95f
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources