Restriction and Transclusion Properties Of AngularJS Directives

Restriction and Transclusion are the properties of AngularJS directives. Restriction property is used to defined the use of directives where as Transclusion property is used to define the place for external content.

Restriction in Directives :

We can define directives in HTML in following ways:

As an Element (E) 

Example :

<my-directive></my-directive>

As an Attribute of an element (A)

Example :

<div my-directive="test" ></div>

As a CSS class (C)

Example : 

<div class="my-directive: test;"></div>

As a Comment (M)

Example :

<!-- directive: my-directive test-->

We can define Restriction property of directive in a following way :

app.directive('myDirective', function () { 
return { restrict: 'EA', scope: { } 
   }; 
});

Element (E) and Attributes (A) directives are most widely used where as Class (C) and Comment (C) directives are rarely used.

Transclusion in directives:


To support Transclusion AngularJS provides two key features :

1) transclude : It’s directives property and it’s need to set to true to support transclusion
2) ng-transclude : ng-transclude itself is a directive, placed inside the another directive template and it define the place where external content will get placed.

Example Without Transclusion:

index.html

<my-directive title=”Transclusion Demo”>Content inside the custom directive</my-directive>

index.js

angular.module('app').directive('myDirective', function () { 
return { restrict: 'EA', 
scope: 
              { title: '@' 
        }, 
template: '<div><div>{{title}}</div><br></div>' 
     }; 
});


Output:

Transclusion Demo
Example With Transclusion:

index.html

<my-directive title=”Transclusion Demo”>Content inside the custom directive</my-directive>

index.js

angular.module('app').directive('myDirective', function () { 
 return { 
     restrict: 'EA', 
     transclude: true, 
     scope: { 
       title: '@' 
           }, 
      template: '<div><div>{{title}}</div><br><div ng-transclude></div></div>' 
    }; 
});

Output:

Transclusion Demo Content inside the custom directive. 

Write a comment
Cancel Reply