AngularJS > Directives

Restricting custom directive in AngularJS

How to restrict a custom directive to be used as class, attribute or element?

In previous posts, we learnt how to create a custom directive. Any custom directive can be either used as element or attribute.

  • Attribute -  <div my-custom></div>.
  • Element - <my-custom></my-custom>.

However, a custom directive can also be used as class <div class="my-custom"></div>.  In order to restrict them to be used in certain ways, we can set restrict properties. Here are the restrict values and their meaning.

  • 'E' = can be used only as element
  • 'A' = can be used only as an attribute
  • 'C' = can be used only as a class attribute
  • 'AEC' = can be used as an attribute or element or class

In below code snippet, we have a controller and its $scope property set. Next, we are creating a directive named 'my-custom-restrict' (normalized name 'myCustomRestrict') where we are setting restrict value as 'AEC' that means my-custom-restrict directive can be used either as "element", "attribute" or as "class attribute".

    var app = angular.module("app", [])
    .controller("CustomDirectiveController", function ($scope) {
        $scope.username = "SheoNarayan";
        $scope.address = "Hyderabad, India";

    app.directive('myCustomRestrict', function () {
        return {
                restrict : 'AEC',
                template: ' UserName: {{ username }}, Address: {{ address }}'

<div ng-app="app" ng-controller="CustomDirectiveController">
    <h2>Restricting custom directive</h2>

    <div><b>Attribute:</b> <span my-custom-restrict></span></div>
    <div><b>Element:</b> <my-custom-restrict></my-custom-restrict></div>
    <div><b>Class:</b> <span class="my-custom-restrict"></span></div>

In the HTML block, we are using my-custom-restrict directive in all three form (Attribute, Element and as Class attribute).


Restrict Custom directive

 Views: 3439 | Post Order: 37

Write for us

Hosting Recommendations