Category Archives: Directives

How to write custom directives in AngularJs?

AngularJs directives controls how HTML is rendered into AngularJs Application. There are  already available directives in angularJs but if you need, can create your own directives.

Custom Directives in AngularJs can be created as shown in following steps:

You will need to register your directive with module

myapp = angular.module(“myapp”, []);

myapp.directive(‘userDetails’, function() {
var directive = {};

return directive;

});

First parameter in directive() is the name of directive. In the above example ‘userDetails‘ is the name of custom directive.Whenever you use ‘userDetails‘ in HTML template it will activate directive.

Second parameter is factory function. This function should return a directive definition when invoked. AngularJS will invoke this function to obtain a JavaScript object which contains the definition of the directive.

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 ‘userDetails' should activate the directive. By setting restrict to A you specify that only HTML attributes named ‘userDetails' should activate the directive. You can also use a value of AE which will match both HTML element names and attribute names.

myapp.directive(‘userDetails’, function() {
var directive = {};

directive.restrict = ‘E';

return directive;

});

There is Template field which will replace the content of directive with specified template.

If we add Template field in directive, as shown below:

myapp.directive(‘userDetails’, function() {
var directive = {};

directive.template = “My first directive: {{textToInsert}}”;

return directive;
});

In your HTML page, if you use <userDetails>

<div ng-controller=”MyController” >
       <userDetails>This will be replaced</userDetails>
</div>

You can give templateUrl to be uploaded to replace content of your directive. As shown below:

myapp.directive(‘div’, function() {
var directive = {};

directive.restrict = ‘E'; /* restrict this directive to elements */

directive.templateUrl = “/myapp/templates/showUserDetail.html”;

return directive;
});

AngularJs will upload template from URL given.


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.