Using AngularJS Directives

What are Directives ?

AngularJS directives are what controls the rendering of the HTML inside an AngularJS application. At a high level, directives are markers on a DOM element that tell AngularJS’s HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children. Directives are a core AngularJS feature. Some of the the framework directives that are used every day are ng-model or ng-repeat. You can also create your own set of directives.

Directive Types

You can implement the following types of directives:

  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives

Register a directive with a module

TDGApp = angular.module("TDGApp", []);

TDGApp.directive('div', function() {
var directive = {};

directive.restrict = 'E';

directive.template = "My directive: {{textToInsert}}";

return directive;

The parameter to the directive() function call is the name of the directive to register. This name is what you use in your HTML templates when you want to activate the directive. In this example I have used the name ‘div‘ which means that the directive is activated every time an HTML element named div is found in the HTML template.

The second parameter is a factory function. AngularJS will invoke this function to obtain a JavaScript object which contains the definition of the directive. The factory function has two properties: A restrict field and a template field. The restrict field is used to set if the directive should be activated by a matching HTML element, or an element attribute. By setting restrict to E you specify that only HTML elements named div should activate the directive. By setting restrict to A you specify that only HTML attributes named div should activate the directive. You can also use a value of AE which will match both HTML element names and attribute names.

The template field is an HTML template that will replace the content of the matched div element. It will work as if the content of the matched div element had not been there, and instead this HTML template had been located in the same place.

Assuming your HTML page had the following code in it:

<div ng-controller="TDGController" >
<div>This div will be replaced by the directive</div>

The directive would be activated when AngularJS finds the inner div element. It would then be replaced with the following code:

My first directive: {{textToInsert}}

AngularJS will interpret this HTML again, so that the interpolation directive actually works. The value of the $scope.textToInsertproperty will be inserted at this point in the HTML. This is the very basics of AngularJS custom directives. Alot more can be done using the same concept to extend HTML.

Write a comment
Cancel Reply