AngularJS Custom Directives Tutorial Part 2 With Examples

In the previous post, we created a simple directive to manipulate the DOM’s behavior. In this post, we are going to describe the directive properties.

Directive Properties

Earlier we looked at the usage of template and templateUrl properties. Now we are going to look at the other directive properties.

  • restrict: This property Determines where a directive can be used (as an element, attribute, CSS class, or a comment).
  • scope : Used to create and isolate the scope.
  • template : Defines the content that should be output from the directive. Can include HTML, data binding expressions, and even other directives.
  • templateUrl : Provides the path to the template that should be used by the directive.
  • controller : Used to define the controller associated with the directive template.
  • controllerAs : Controller alias at the directive scope.
  • priority : Used to specify the order in which the directives are applied when there are multiple directives defines on a single DOM element.
  • link : Defines the function used for DOM manipulation tasks.
  • compile : The compile function deals with transforming the template DOM.
  • transclude: Extract the contents of the element where the directive appears and make it available to the directive. The contents are compiled and provided to the directive as a transclusion function.

You can check the official Angular documentation for more details.

Restriction in Directives

When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option.
Angular provides different options to restrict the usage of directives.

Following section demonstrates the usage of the restrict options.

‘A’ – This directive is applied only when attribute name is matched.

‘E’ – This directive is applied only when element name is matched.

‘C’ – This directive is applied only when class name is matched.

‘M’ – used in a comment.

We can also combine these restrictions as needed:

‘AEC’ – matches either attribute or element or class name

Syntax for Using Directive properties

Following script demonstrates the syntax for using directive properties. You don’t have to use all of these properties to create a directive. You can use these directive properties depending on your requirement.

Using Directive Properties

The following example demonstrates the usage of above-mentioned properties to create a directive called myEmployee.

We can use the  myEmployee directive as an attribute or element. We use link function in the above example to alert a message.

You will see the following output in your browser.


That’s all for now and we will look deeper into these properties in the coming posts.

By admin

Leave a Reply

%d bloggers like this: