« Previous | 1 | 2 | 3 | Next »
Custom directives are used in AngularJS to extend the functionality of HTML.

Custom directives are defined using "directive" function.

A custom directive simply replaces the element for which it is activated.

AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive.

AngularJS provides support to create custom directives for following type of elements.

Element directives − Directive activates when a matching element is encountered.

Attribute − Directive activates when a matching attribute is encountered.

CSS − Directive activates when a matching css style is encountered.

Comment − Directive activates when a matching comment is encountered.
Understanding Custom Directive
Define custom html tags.

Define custom directive to handle above custom html tags.
var mainApp = angular.module("mainApp", []);
//Create a directive, first parameter is the html element to be attached.
//We are attaching student html tag.
//This directive will be activated as soon as any student element is encountered in html
mainApp.directive('student', function() {
//define the directive object
var directive = {};
//restrict = E, signifies that directive is Element directive
directive.restrict = 'E';
//template replaces the complete element with its text.
directive.template = "Student: <b>{{student.name}}</b> ,
Roll No: <b>{{student.rollno}}</b>";
//scope is used to distinguish each student element based on criteria.
directive.scope = {
student : "=name"
//compile is called during application initialization. AngularJS calls it once when html page is loaded.
directive.compile = function(element, attributes)
{ element.css("border", "1px solid #cccccc");
//linkFunction is linked with each element with scope to get the element specific data.
var linkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
return linkFunction;
return directive;
mainApp.controller('StudentController', function($scope) {
$scope.aarif = {};
$scope.aarif.name = "aarif m";
$scope.aarif.rollno = 1;
$scope.rahul = {};
$scope.rahul.name = "rahul kr.";
$scope.rahul.rollno = 2;
AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script.
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>
« Previous | 1 | 2 | 3 | Next »

copyright © 2014 - all rights riserved by javatechnologycenter.com