AngularJS Custom Directive Template with Example

Here we will learn custom directives in angularjs, use of custom directives in angularjs and how to build our own custom directives in angularjs with example.

What are the Directives in AngularJS?

Generally, directives in angularjs are used to extend the functionality of HTML controls by adding special behavior to HTML dom elements.

 

In angularjs we have built-in directives available that are ng-model, ng-bind, ng-init, etc. like these directives we can create our own custom directives in angularjs and these directives functionality will be activated in our angularjs applications using compile method wherever we called these directive elements.

Rules to Create Custom Directive in AngularJS

We need to follow some of the rules to create custom directives in angularjs

 

  • Generally it's better to follow CamelCase to create directive name but as we know HTML is case-insensitive so it's better to use lower case to create directive.
  • You can give any name format to custom directive like studentmarks or student-marks, Always try use dash delimited format like e.g. student-mark.

AngularJS Custom Directive Syntax

In angularjs, we can create custom directives by using .directive function. Following is the syntax of creating custom directives using directive function in angularjs.

 

<script type="text/javascript">

var app = angular.module('angularmoduleapp', []);

app.directive('tutDirective'function () {

return {

template: 'Welcome to Tutlane.com'

};

});

</script>

<div ng-app="angularmoduleapp" tut-directive></div>

If you observe the above syntax, we created a custom directive called "tutDirective". To invoke this custom directive, we need to use - separated name like tut-directive.

AngularJS Custom Directive Example

Following is the example of creating a custom directive using .directive function in angularjs application.

 

Live Preview

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>

AngularJs Adding Directives to Modules Example

</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script type="text/javascript">

var app = angular.module('angularmoduleapp', []);

app.directive('tutDirective'function () {

return {

template: 'Welcome to Tutlane.com'

};

});

</script>

</head>

<body>

<div ng-app="angularmoduleapp" tut-directive></div>

</body>

</html>

If we run above custom directive example, we will get output like as shown below.

Output of AngularJS Custom Directive Example

Following is the output of custom directives example in angularjs.

 

Welcome to Tutlane.com

This is how we can create custom directives in angularjs based on our requirements.