Directives in Angularjs

Directives in Angularjs

Directives are markers on a DOM element which tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element. In general most of everything is a directive in AngularJS.
AngularJS directive can be used as:-
 Element name
 Attribute
 Class
 Comment
-Life cycle of directive begins and end only under the process of bootstrapping i.e. before the page is rendered.
-Below are the four functions which executes during the life cycle of directive if those are there in directive.
a) compile :- allows the directive to manipulate DOM before it is complied and linked, during this phase it modify the DOM and directives i.e. by adding removing and changing.
b)Controller :- controller provides the communication. Sibling and child controller can request for information to their siblings and parent’s controller.
c) pre-link :- Within this function manipulation with $scope is done(if any) so that the manipulated scope can be used in post-link function.
d) post-link : – This is the method which performs most of the work of the directive.
So if all four functions are used then structure will be something like below:-

.directive("mydirective",function () {
return {
controller: function() {
//code for controller.
},
compile:{
// compile related code.
return {
pre: function() {
// code for pre-link.
},
post: function() {
// code for post-link.
}
};
}
}
})

Signature for both i.e. pre and post link are same, the main difference is in the order those are executed. In general you will be not seeing more usage of pre-link function. Mostly controller and post-link are enough for handing basic purpose of a directive. In those case ‘link’ will be simply referring to the ‘post-link’.

.directive("mydirective",function () {
return {
controller: function() {
//code for controller.
},
link: function() {
// code for post-link.
}
}
})

Below is the sample code for creating a custom directive. In this directive things are very simple and only link method is being used. The thing to notice here is that we are not using the ‘$scope’ inside the link function, instead we are using scope which is called ‘isolated scope’.

index.html:-

<html>
   <body>
<div ng-app="mainApp">
	     Enter Percentage :- <input ng-model="percentage"></input>

	    <percentage-dir value="percentage" ng-init="percentage = 15"></percentage-dir></div>
<script src ="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

    <script>
        var mainApp = angular.module('mainApp', []);
        
		  mainApp.directive("percentageDir", function (){
		    return {
		        restrict: 'E',
		        scope: {
		            value: '=',
		        },
		        templateUrl: 'directivetemplates/percentageTemplate.html',
		        link: function(scope, element, attrs) {
		           element.on('click', function () {
	                  alert('You cannot write Here.');
	               
	              });
		           scope.canvas = element.find('canvas')[0];
		           scope.context = scope.canvas.getContext('2d');
		 
		           scope.$watch('value', function(currentValue) {
		             fillWidth = Math.ceil(currentValue / 100 * scope.canvas.width);
		             scope.context.fillStyle = "#cccccc";
		             scope.context.fillRect(0, 0, scope.canvas.width, scope.canvas.height);
		             scope.context.fillStyle = "#0000FF";
		             scope.context.fillRect(0, 0, fillWidth, scope.canvas.height);
		           });
		        }        
		    };
		});
      </script>
</body>
</html>

directivetemplates/percentageTemplate.html:-

<canvas width='200' height='30' style="border-style: solid;border-width: 2px">
</canvas>

Hope this will be helpfull to someone.