
In AngularJS, Directives are a way to extend HTML syntax, create reusable components, and create custom behaviors for existing DOM elements. AngularJS comes with a set of built-in directives, but we can also create our own custom directives to add additional functionality.
A custom directive in AngularJS is created using the directive()
function. It takes two arguments: the name of the directive and a factory function. The factory function is responsible for returning the configuration object for the directive.
The configuration object for a directive consists of several properties:
restrict
: Specifies how the directive can be used. It can be used as an element, attribute, class, or comment. The values are'E'
,'A'
,'C'
, and'M'
respectively.template
: Specifies the HTML content that should be used for the directive.templateUrl
: Specifies the URL of an HTML file that should be used for the directive.scope
: Specifies the scope of the directive.link
: Specifies a function that will be executed after the directive is compiled.
Here’s an example of a custom directive that adds a confirmation dialog to a button:
<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js
<meta charset="utf-8">
<title>Custom Directive</title>
</head>
<body ng-app="myApp">
<button confirm-click="Are you sure you want to delete this item?">Delete Item</button>
<script>
var app = angular.module('myApp', []);
app.directive('confirmClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
var message = attrs.confirmClick;
if (message && confirm(message)) {
scope.$apply(attrs.ngClick);
}
});
}
};
});
</script>
</body>
</html>
In this example, the confirmClick
directive is defined with the directive()
function. The restrict
property is set to 'A'
to indicate that it should be used as an attribute. The link
property is set to a function that binds a click
event to the element. When the button is clicked, a confirmation dialog is displayed with the message specified in the confirm-click
attribute. If the user confirms the action, the ngClick
directive is executed.
Here’s a comparison table between built-in directives and custom directives:
Built-in Directives | Custom Directives |
---|---|
Predefined by AngularJS | Defined by the developer |
Available for use out of the box | Created using the directive() function |
Can be used with any AngularJS application | Can be used only with the application where it is defined |
Examples: ng-model , ng-repeat , ng-if | Examples: confirm-click , show-on-hover , uppercase-text |
In summary, custom directives in AngularJS allow us to create our own reusable components and behaviors that can be used within our application. They are defined using the directive()
function, and their configuration object specifies how they should be used and what behavior they should provide.