Objectives and outcomes

In this tutorial we are going to learn about Custom Directives in angular-js. We use custom directives to enhance the functionality of html document. We can define our own directives using directive() method. Well if you are not familier with directives then you should go through our AngularJS Directives tutorial. We can create custom directives for the following : elements, attributes, CSS and comment.



HTML code:

<html>
<head>
<meta charset="utf-8">
<title>AngularJS custom directives</title>
<script src="angular-1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="custom_dir" ng-controller="custom_control">
<numeric val="first"></numeric><br/>
<numeric val="second"></numeric>
</div>
</body>
</html>


Javascript

<script>
var app = angular.module("custom_dir",[]);

app.directive('numeric',function()
{
var directive = {};
directive.restrict = 'E';  // E signifies element directive
	
// Below template is shown where numeric element is found
directive.template = "Number: <b>{{numeric.val}}</b>, Half of number: <b>{{numeric.half}}</b>";
	
// Scope is used to distinguish numeric element
directive.scope = {
numeric : "=val"
}
	
directive.compile = function(element,attributes)
{
		
var link = function($scope,element,attributes)
{
element.html("Number: <b>"+$scope.numeric.val+"</b> , Roll no: <b>"+$scope.numeric.half+"</b><br/>");
element.css("background-color", "#cccc32");
}
		
return link;
}
	
return directive;
});

app.controller("custom_control",function($scope)
{
$scope.first = {};
$scope.first.val = 16;
$scope.first.half = 8;
	
$scope.second = {};
$scope.second.val = 25;
$scope.second.half = 12.5;
});
</script>





Angular-js finds the matching element by using compile() method. Element is processed using link() method based on the scope of directive.