restrict
defines how a custom directive can be used in an HTML file.- It determines whether the directive can be applied as an Element (
E
), Attribute (A
), Class (C
), or Comment (M
).
1. restrict: 'E'
(Element Directive)
- Used as a custom HTML tag.
- Suitable for creating reusable components like cards, headers, footers.
- Encapsulates UI into separate elements.
Example: Creating a <custom-card>
Directive
Step 1: Define Directive in JavaScript
var app = angular.module("myApp", []);
app.directive("customCard", function () {
return {
restrict: "E", // Used as an element
template: "<div class='card'><h3>Custom Card Component</h3></div>"
};
});
Step 2: Use in HTML
<custom-card></custom-card>
✔ Explanation:
<custom-card></custom-card>
is a custom HTML element.- The directive replaces it with the
template
content.
2. restrict: 'A'
(Attribute Directive)
- Used as a custom attribute in an existing element.
- Ideal for modifying behavior or styling (e.g., changing color, adding effects).
Example: Creating a highlight
Directive
Step 1: Define Directive in JavaScript
app.directive("highlight", function () {
return {
restrict: "A", // Used as an attribute
link: function (scope, element) {
element.css("background-color", "yellow");
}
};
});
Step 2: Use in HTML
<p highlight>This paragraph will have a yellow background.</p>
✔ Explanation:
- The
highlight
directive modifies the background of the<p>
element. - Works as a behavior-based directive rather than a UI component.
🔹 3. restrict: 'E'
vs restrict: 'A'
– When to Use What?
Restrict Type | Usage Style | Best For | Example |
---|---|---|---|
E (Element) | <custom-card></custom-card> | UI Components, Encapsulated Elements | Reusable UI blocks (e.g., <custom-navbar> , <user-profile> ) |
A (Attribute) | <p highlight></p> | Behavior, Styling, Event Handling | Adding effects, validation, DOM manipulation |