AngularJS_logo.svgWhat is a custom directive?

In my last post I’ve described what’s a directive and the types of directives available in AngularJS. But in AngularJS you’re not restricted to what is available, you have the ability to create you own directive too.

What are the ingredients that makes up a custom directive?

A very basic custom directive will contains the module.directive API to register it. The first parameter is the name and the second parameter is the function that returns configuration object.

Below is I have created an directive that is an element with a template that display a simple Hello, World! message in html.

angular.module('app', [])
.directive('helloWorld', function () {
    return {
        restrict: 'E',
        template: '<b>Hello, World!</b>'
    };
});
<hello-world></hello-world>

Let’s break it down.

Restrict define the type and there are 3 types you can choose from. You can define them individually or use them in combination:

  • ‘A’ – Attribute
  • ‘E’ – Element
  • ‘C’ – Class

Template allow you to add html to your directive, and this means that you can reuse this html code in any part of your single page application.  There is another way of specifying a template, by providing a html file to the templateUrl property. (Tip: templateUrl will only work on web server, so it wont work running this code locally in a browser)

angular.module('app', [])
.directive('helloWorld', function () {
    return {
        restrict: 'E',
        templateUrl: 'template.html'
    };
});

If you would like a copy of these examples in this post, you can obtain them from GitHub:
https://github.com/csharpguy76/LearnAngularJS

Shares