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.
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.
We need to follow some of the rules to create custom directives in angularjs
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
.
Following is the example of creating a custom directive using .directive
function in angularjs application.
<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.
Following is the output of custom directives example in angularjs.
This is how we can create custom directives in angularjs based on our requirements.