AngularJS Custom Directives
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.
We create new directives using the .directive method; the arguments we provide to this are the name of the new directive and a function that creates the directive.ngularJS provides support to create custom directives for following type of elements.
- Element directives(E)- Directive activates when a matching element is encountered.
- Attribute (A)− Directive activates when a matching attribute is encountered.
- CSS(C) -Directive activates when a matching css style is encountered.
- Comment(M) − Directive activates when a matching comment is encountered
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 -->
<html >
<head>
<title>AngularJS</title>
</head>
<script src = "https://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>