AngularJS provides several directives to manipulate the DOM’s behavior. Earlier we looked at some of the built in directives like ng-app, ng-controller, ng-repeat etc. You can check out the official angular API documentation for more directives.  Although angular provides many built in directives, sometimes we will face some scenarios in which we need to write our own directive to achieve a specific task.  In this series of tutorials, we will guide you to write a good Angular directive.

In AngularJS Custom Directives Tutorial – Part 1, we will start with a simple example to create a directive.

Creating Directives

We use module.directive API to register our directive. You must make sure not to prefix your directive with ng since it may conflict with other built in directives.

In this post, we will create a template-expanding directive. Sometimes we have to use the same template in multiple locations in our applications. We can use a custom directive to simplify the use of these common directives. That makes the code more manageable.

The following example demonstrates the usage of module’s directive API to create our directive. In this example,we use directive’s template property to create a directive called myEmployee.


Following code demonstrates how to use our myEmployee directive.


You will see the following output in your browser.

AngularJS Custom Directives Tutorial - Part 1 With Examples

The template attribute defines the content that should be the output from the directive. We can include HTML, data binding expressions, and even other directives.
Unless the template is too small, it’s always better to break it apart into its own HTML file and load it with the templateUrl option.

We will modify the above example to demonstrate the usage of templateUrl option property of the directive.


There isn’t any change in the index.html file.


The my-employee.html file contains the contents of the template used by the directive.


You will see the same output in this case as well.

That’s all for now and We will cover all the topics related to custom directives in the following posts.

By admin

Leave a Reply

%d bloggers like this: