AngularJS | Custom Directives

AngularJS custom directives are used to extend the HTML functionality. Custom directives is defined using 'directive' AngularJS function. AngularJS has a set of built-in directives which has many default functionalities (HTML attributes with the prefix ng- like ng-app, ng-init and ng-scope).

Types of Directive

These are the following types of AngularJS Directives:

  1. Element directives
  2. Attribute directives
  3. CSS class directives
  4. Comment directives

How to define and use AngularJS Directives

I can explain you the steps of creating custom Directive and use in HTML template.

Defining the JS


var app = angular.module('myApp', []);

app.directive('exampleDirective', function() {
    return {
        restrict: 'E',
        scope:{
        	panelTitle: '@',
        	panelBody: '@',
        },
        template: '
{{panelTitle}}
{{panelBody}}
', replace: true, link: function(scope, elm, attrs) { } }; });

scope - panelTitle and panelBody is the two scope where we can pass title and body content.

template – Created a HTML Template for making Panel head and body. This specifies the HTML markup that will be produced when the Directive is compiled and linked.

restrict – This provides a way to specify how a Directive should be used in HTML.

replace – This specifies if the generated Template will replace the HTML element on which the Directive is attached.

Place Directives in HTML

<example-directive panel-title="Panel Title" panel-body="Panel Body"></example-directive>

In this case, the name must be written using dashes and each dash represents a capital letter (panelTitle changed to panel-title when come to template) from the directive definition.

Demo

shanidkv's picture