AngularJS – Directive Restrictions

Directives are markers on a DOM element which attach a special behavior to it. For example,ng-show and ng-hide will make to show or hide an respective elements using this directives. Like wise,static HTML does not know how to create and display a date picker widget. To teach HTML this new syntax we need a directive. The directive will somehow create an element that behaves like a date picker.

The Angular approach is to use a directive to extend HTML. So, a directive for a date picker can look like this:


Or it could look like this:

<input type="text" date-picker/>

This approach to creating UI components is intuitive and clear. You can simply look at the element to know what it is supposed to be!

Building Custom Directives:

An Angular directive comes in four flavors in terms of appearance.

  1. A new HTML element (<date-picker></date>).
  2. An attribute on an element (<input type="text" date-picker/>).
  3. As a class (<input type="text" class="date-picker"/>).
  4. As comment (<!--directive:date-picker-->).


Lets say superman is an element just look like this <superman></superman> where we will be showing an alert message like “I am Working”.

  1. var app = angular.module(“superhero”, [])
  2. app.directive(“superman”, function(){
  3. return {
  4. restrict: “A”,
  5. link: function(){
  6. alert(“I’m working”);
  7. }
  8. };
  9. });

From here, instead of having superman as an element, let’s do a div with superman as an attribute:

  1. <div ng-app=“superhero”>
  2. <div superman></div>
  3. </div>

Now if we refresh, you’ll see the alert saying “I’m working” Another restriction we can use is “C” for class. If we change restrict to “C” and refresh without changing anything, we can see that nothing happens. We need to change the directive from an attribute to a class of the div.

  1. <div ng-app=“superhero”>
  2. <div class=“superman”></div>
  3. </div>

The last restriction is “M” for comment. If we change restrict to “M” and create a comment starting with “directive:”


  1. <div ng-app=“superhero”>
  2. <!– directive:superman –>
  3. </div>

You can even try like this restrict: 'AE'//attribute and element. By default it will be for attribute that is restrict:'A'.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s