AngularJS Directive’s ‘Restrict’ Real World Guide

While trying to wrangle custom directives in AngularJS, I’ve found the restrict property a bit tough to understand even after reading the guide:

The restrict option is typically set to:

  • 'A' – only matches attribute name
  • 'E' – only matches element name
  • 'C' – only matches class name

These restrictions can all be combined as needed:

  • 'AEC' – matches either attribute or element or class name

Here’s a real world example of each one in use. For these examples, we’ll define our directive as:

directive('exampleDirective', function(){
    return {
        restrict: 'A',
        template: 'This is an example directive',
    }
});

Also notice that even though our directive is named ‘exampleDirective’, Angular converts it to ‘example-directive’ when compiling the html.

 

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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