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
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 –