Angularjs custom directives:
AngularJS provides the facility to create the custom directives. Custom directives extends the functionality of HTML. Custom directives are created using “directive” function. AngularJS simply replace the element with custom directive for which it actsivated.
Important points:
If custom directive name consist of two or more words like testDirective then when invoking we must use – separated name like test-directive.
We can invoke a custom directive by using:
Element name: like
<test-directive></test-directive> |
Attribute: like
<div test-directive></div> |
CSS Class: like
<div class="w3-test-directive"></div> |
Comment: like
<!-- directive: w3-test-directive --> |
Important points:
To invoke the directive from a comment add the value “M” to the restrict property. We also have to add the replace property otherwise the comment would be invisible.
To invoke the directive from a CSS class name add the value “C” to the restrict property.
Example Explanation:
The ng-app directive initializes the application. We create a custom directive named testDirective and use it using Element name and Attribute.
Example:
<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> <body ng-app="testApp"> <h2>Using Element Name:</h2> <test-directive></test-directive> <h2>Using Attribute:</h2> <div test-directive></div> <script> var app = angular.module("testApp", []); app.directive("testDirective", function() { return { template : "<h3>Custom directive message.</h3>" }; }); </script> </body> </html> |
Try it:
Angularjs custom directive restrict:
As we discussed above a custom directive can be invoked by using Element name, Attribute, CSS Class or Comment. We can also restrict custom directives to only be invoked by some of the above methods. We have add restrict property to restrict the directive call.
The restrict property values:
E: Element name
A: Attribute
C: Class
M: Comment
Note: EA is the default value for restrict property i.e. Element names and attribute names can invoke the directive.
Example Explanation:
The ng-app directive initializes the application. We create a custom directive named testDirective and use it using Element name and Attribute. As we restrict the directive call to Element Name only so directive call using Attribute will not invoke the directive.
Example:
<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> <body ng-app="testApp"> <h2>Using Element Name:</h2> <test-directive></test-directive> <h2>Using Attribute:</h2> <div test-directive></div> <script> var app = angular.module("testApp", []); app.directive("testDirective", function() { return { restrict : "E", template : "<h3>Custom directive message.</h3>" }; }); </script> </body> </html> |