- Directives extend HTML by creating reusable components.
- They allow DOM manipulation, event handling, and dynamic behavior.
- Built-in directives:
ngModel
,ngClick
,ngClass
, etc. - Custom directives are created using
directive()
function.
1. Basic Custom Directive
This directive changes text color dynamically.
Example: Change Text Color
var app = angular.module("myApp", []);
app.directive("changeColor", function () {
return {
restrict: "A", // Use as an attribute
link: function (scope, element, attrs) {
element.css("color", attrs.changeColor); // Set color dynamically
}
};
});
Usage in HTML
<p change-color="red">This text will be red</p>
<p change-color="blue">This text will be blue</p>
✔ Explanation:
restrict: "A"
→ The directive is used as an attribute.element.css("color", attrs.changeColor)
→ Reads the color from the attribute.
2. Custom Directive for Hover Effects
This directive changes the background color on hover.
Example: Hover Effect Directive
app.directive("hoverEffect", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
var defaultColor = element.css("background-color");
element.on("mouseenter", function () {
element.css("background-color", attrs.hoverEffect || "yellow");
});
element.on("mouseleave", function () {
element.css("background-color", defaultColor);
});
}
};
});
Usage in HTML
<div hover-effect="lightblue">Hover over me</div>
<div hover-effect="pink">Hover over me</div>
✔ Explanation:
- Uses
mouseenter
andmouseleave
events. - Changes background color based on
hover-effect
attribute.
3. Custom Directive for Adding/Removing Elements
This directive creates a button that adds/removes elements dynamically.
Example: Dynamic Element Manipulation
app.directive("addRemove", function () {
return {
restrict: "E", // Use as an element
template: `
<button ng-click="addItem()">Add Item</button>
<ul>
<li ng-repeat="item in items track by $index">
{{ item }} <button ng-click="removeItem($index)">Remove</button>
</li>
</ul>
`,
link: function (scope) {
scope.items = [];
scope.addItem = function () {
scope.items.push("New Item " + (scope.items.length + 1));
};
scope.removeItem = function (index) {
scope.items.splice(index, 1);
};
}
};
});
Usage in HTML
<add-remove></add-remove>
✔ Explanation:
- Uses
ng-repeat
to dynamically add/remove items. - Uses
ng-click
to trigger the actions.
Best Practices for DOM Manipulation in AngularJS Directives
✔ Use link
function for DOM changes.
✔ Avoid direct DOM manipulation; use AngularJS bindings when possible.
✔ Detach event listeners in $destroy
to prevent memory leaks.