AngularJS - Create directive

By xngo on August 21, 2019

In addition to the built-in directives, AngularJS allows you to create your own directives. New directives are created using the module.directive(name, directiveFactory) function. It will register the directive name and use the directiveFactory function to tell AngularJS how this new directive should behave. The directiveFactory function is simply a function that returns an object with different options that will dictate the new directive's behaviour.

Create new directive

Let's say that you need to display the same customer's information template in different places. This is a good opportunity to create your own directive that can be reused. It will simplify your template.

Here is an example showing the creation of the new directive called myCustomer. It will display the name and the age of the customer.

<div ng-app="myApp">
    <my-customer ng-init="customer={name:'Joe', age: 11}"></my-customer>
</div>
 
<script>
var app = angular.module("myApp", []);
app.directive("myCustomer", function() {
    return {
        template: 'Name: {{customer.name}} Age: {{customer.age}}'
    };
});
</script>

Output

Name: Joe Age: 11

Notice that the directive name myCustomer is different when you invoke it(i.e <my-customer>). When you name your directive, it must be in camel case(e.g. myCustomer). But, when you invoke it, it must be separated by an hyphen(-)(e.g. my-customer). That is not all. You can invoke your directive in different ways:

  • As an element name, <my-customer></my-customer>.
  • As an attribute, <div my-customer></div>.
  • As a class, <div class="my-customer"></div>.
  • As a comment, <!-- directive: my-customer -->.

Invoke restriction

You can restrict how your directive can be invoked. It is controlled by the restrict property. By adding the value A to the restrict property, the directive can only be invoked by attributes.

var app = angular.module("myApp", []);
app.directive("myCustomer", function() {
    return {
        restrict : 'A',  
        template: 'Name: {{customer.name}} Age: {{customer.age}}'
    };
});

The possible restriction values are:

  • E for Element name
  • A for Attribute
  • C for Class
  • M for Comment

By default, directives are restricted to EA.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.