AngularJS facilitates extending the HTML, with new attributes, called "Directives". It provides a set of built-in directives that offer functionality to your applications, like ng-app, ng-init, ng-model. AngularJS also enables us to define our own custom directives.
Using Code
Let's create a custom directive, with the following code.
- <script>
- var app = angular.module("myApp", []);
- app.directive("myOwnDirective", function() {
- return {
- template : "<h1>This is my directive!</h1>"
- };
- });
- </script>
We can call/use a custom directive in the following four ways.
- Attribute
<div my-own-directive></div> - Class
<div class="my-own-directive"></div> - Element name
<my-own-directive></my-own-directive> - Comment
- <script>
- var app = angular.module("myApp", []);
- app.directive("myOwnDirective", function() {
- return {
- restrict : "M",
- replace : true,
- template : "<h1>This is my directive!!</h1>"
- };
- });
- </script>
- <!-- directive: my-own-directive -->
From the above discussion, we can see that we can use directives in different ways. It is always recommended to use the directives through tag name and attributes over comment and class names. It will be easier to determine what directives an element matches.
Note: You might be confused that directive name (myOwnDirective) is different when we use it (my-own-directive). Directive name follows camel case and the implementation follows hypen(-) in the next capital letter.
Properties of Custom Directive
replace
The replace property in directives indicates that the element to which the directive is being applied (<my-own-directive> in that case) should remain (replace: false) and the directive's template should be appended as its child.
- <div ng-controller="Ctrl" class="ng-scope">
- <div class="ng-binding">hello</div>
- </div>
- <div ng-controller="Ctrl" class="ng-scope">
- <my-dir>
- <div class="ng-binding">hello</div>
- </my-dir>
- </div>

Join the conversation! Your thoughts help the community grow.