Custom Directives in AngularJS

With custom directives in AngularJS we can standardize our own way to control the rendering the HTML elements in an AngularJS application. In this article we will be creating a simple AngularJS application demonstrating the concept of custom directives.

Following types of custom directives can be created in AngularJS –

  • Element directives – This directive activates when a matching element is found.
  • Attribute directives – This directive activates when a matching attribute is found.
  • CSS class directives – This directive activates when a matching CSS style is found – least used
  • Comment directives – This directive activates when a matching comment is found – least used

directive() – This function is used to register a directive. The first parameter is the name of the directive that we want to register, while the second parameter is a factory function call that returns a JavaScript object containing the registered directive definition.

Below are some of the object properties and functions that we will be using along with the purpose they serve –

  • restrict – to specify the type of the directive that we are creating
  • template – what content needs to be replaced for matching directives in HTML
  • templateUrl – same as template, instead we can put the HTML content to be replaced, inside a separate HTML file.
  • scope – to be able to uniquely identify multiple custom directives in the HTML based on the property we specify within this “scope” property and bind separate values accordingly.
  • compile function – does the initial configuration
  • link function – compile function does the initial configuration, which later calls the link function, which further does the needed data binding before finally rendering it on the browser.

Below is a sample AngularJS application that depicts all that we have discussed –

When our AngularJS application runs, the value of the directive.template property repeats itself as-it-is to appear the same number of times as the directive (<hello …>) appears in the HTML. The data binding happens later within the compile function when the link function gets called. It is important that you understand this bit.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.