AngularJS Directive

Previous Next: AngularJS Modules

AngularJS Directives extend HTML which means directives can be an attribute, element name, comment or CSS class. AngularJS has build in directives. These are prefix with ng- like ng-app, ng-bind, and ng-model.

<div> 
     <span ng-bind="abc"></span>

     <customer-grid></customer-grid>

     <p make-color-red> this is my custom attribute directive </p>
</div>

In above example, ng-bind is angular build-in attribute directive, whereas customer-grid is custom element directive and make-color-red is custom attribute directive.

Next we will learn how to create custom directives, for the complete list of build-in AngularJS directives check out AngularJS directives reference

Lets create a custom directive

AngularJS allows us to create own directives. We can create a custom directive using .directive function. Lets see an example :-

// define a angular module, we will read module in next chapter
var techkizApp = angular.module('techkizTutorial', []);

// create custom directive, Directive name is customerGrid. It can be an attribute, element name, comment or CSS class.
techkizApp.directive('customerGrid', function() {

  return {
    // restrict determine the type of directive, it's default value is 'EA'
    restrict: 'E',
    
    scope: {
      customerInfo: '=info'
    },

    template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}}',
    
    /** 
    templateUrl: 'customer-grid-template.html',
        template url can be used in place of template, only one can use in a directive. 
    **/
  };
});

In above example
1) In line 2, First we define a module because directives are registered on modules. We will read AngularJS modules in next chapter.
2) In line 5, We define directive using module.directive API. It has two parameters, normalized directive name and factory function which return configuration object.

Directive name

A directive name must be in camelCase, but when we use directive in html we must use dash-delimited name e.g. customer-grid. Angularjs normalizes directive name to match. The normalization follows:

  • Strip x- and data- from the front of the element/attributes.
  • Convert the :, -, or _ delimited name to camelCase.
Directive Configuration Object

Directive configuration object have difference object that determine how to directive behave. This object has following properties :-

  1. restrict : determine the type of directive. Possible value will be :-
    • E – to make element directive
    • A – to make attribute directive
    • C – to make class directive
    • M – to make comment directive

     
    Default value is ‘EA’, we can use a signle value or a combination of any of these.

  2. scope :

Previous Next: AngularJS Modules