⚙️ Introduction to Custom Directives in AngularJS
Extend HTML with your own powerful, reusable components using custom directives.
While AngularJS provides several built-in directives (like ng-model, ng-repeat), it also lets developers create their own custom directives to encapsulate and reuse logic or templates across the application.
🧠 Why Use Custom Directives?
- Encapsulate reusable HTML and behavior.
- Improve code organization and maintainability.
- Create reusable widgets/components.
🛠 Basic Example
Let’s create a custom directive called helloWorld that displays a message.
// app.js
var app = angular.module('myApp', []);
app.directive('helloWorld', function() {
return {
restrict: 'E',
template: '<h3>Hello from Custom Directive!</h3>'
};
});
Use it in HTML as:
<hello-world></hello-world>
🧩 Restrict Options
The restrict property tells Angular how the directive can be used:
'E'– Element name (e.g.,<my-directive>)'A'– Attribute (e.g.,<div my-directive>)'C'– Class (e.g.,<div class="my-directive">)'M'– Comment (rarely used)
🔗 Real-World Use Cases
- Reusable UI widgets (e.g., tooltips, tabs, sliders)
- Form validation logic blocks
- Shared content blocks (e.g., headers, footers, product cards)
scope bindings and define isolated scopes.


