How to Create a Custom Directive in AngularJS :Step by Step Explained

For extending the functionality of HTML in angular JS, customs directives are used. The directive is defined by the users for extending HTML functionalities through the desired functions. Any element for which the customs directives are generated gets replaced by it. Although lots of directives are present in angular JS, there might be cases that require custom directives.

The following elements can be used for creating custom directives by angular JS. The activation of a directive is based on the type of a directive.

  • Element directives: Whenever there is an element that matches, the activation of the directive takes place.
  • Attribute: With the matching of an attribute, the directive gets activated. 
  • CSS: With the matching of a CSS style, the directive is activated.
  • Comment: On the encounter of a matching comment, the directive gets activated.

Registering a Module with that of a Directive

 Program for module registering to a directive 

Source

A directive() function call has been made in the module. Through this call, a new directive can be registered. 

The directive to register has a specific name which is used as the first parameter to the function. This name appears in the HTML template when the user wants to activate the directive. In the code, the name ‘div’ is used. This means that every time the HTML element with the name ‘div’, matches an element in the HTML template, the directive is activated.

A factory function is used as a second parameter in the function directive. On invoking the function, a directive definition should be returned. The function will be invoked by the angular JS, which will return an object of JavaScript that will contain the directive definition. The above code shows the return of the JavaScript object.

Two properties exist with the returned object; a restrict, and a template field.

Whether the activation of a directive should follow by the matching of an HTML element or by the matching of an attribute, will be set by the restrict field. We can specify if a directive should get activated by HTML elements through setting restrict to E and setting it to A, the users can specify that the directive will be activated only through the attribute matching of an element. Specifying both AE will allow the matching of both an HTML element and an attribute.

The other property i.e. the template field is involved in replacing the contents of the matching div elements.

If the HTML in a HTML page is like this

<div ng-controller=”MyController” >
                <div>This div will be replaced</div>
</div>     

The activation of the directive that was added will be done when the div element is found out by angular JS.

Data Binding in Angular

Binding data meaning is to be known before understanding the concept of angular data binding. With the changes in the value of data, there are automatic changes with the elements that are bound to the data. It can be one-way or can be a two-way process. Angular data binding is of four types; Interpolation, Property Binding, Event Binding, and Two-Way Data Binding.

Read: Difference Between Angular vs AngularJs 

Creation of a Custom Directive

A few steps involved in the creation of a custom attribute directive are;

Step1: A directive is created by a class decoration through using @Directive decorator.

Step2: Renderer and Services ElementRef are injected.

Step 3: The directive is to be registered with the module.

Step 4: the directive is to be used.

  • Application of a custom directive to an element of HTML makes the element to be known as “HOST ELEMENT”.

The example will show the creation of a custom directive in angular JS. A div tag will be injected when the directive is being called.

An example of code for the creation of custom directive

Source

Explanation of the code:

  • A module is first created for the application of angular. The creation of the module is important for creating custom directives, because with the use of this module, the custom directive will be created.
  • A custom directive with the name ‘ngGuru’ is created and a function is defined that will contain the custom code of the directive.
    • Defining the directive, the letter G is capitalized in ngGuru. While accessing from the div tag, the name remains as ng-guru. The custom directives that are defined in an application are understood through this format in angular. The letter ‘ng’ prefixes the name of any custom directives and a hyphen symbol ( –) should be used whenever a directive is being called. Lastly, the letter that follows the “ng” can either be lowercase or uppercase while the directive is defined.
  • The parameter is defined by angular i.e. the template parameter is used. It is defined in a way that whenever there is a use of the directive, the template value is to be used and injected while calling the code.
  • The program is making use of the “ng-guru” directive which is custom created. While doing this, the template value will get injected here.

Successful execution of the code will generate the following output.

Output of the code 

Source

In the output the custom directive i.e. the ng-guru can be seen with the defined template. The template is defined for displaying a custom text.

Scope of AngularJS Directives

The controller is bound to the view through the scope which manages the flow of data between the controller and the view. The custom directives in angular will by default are accessing the scope object that is contained in the parent controller. Therefore, the process becomes an easy one where the data that is passed to the controller can be used by the custom directive. 

An angular custom directive example is shown below to show the use of scope on the custom directive. An example of code 

Source

Explanation of the code

  • A controller with the name “DemoController” is created first. A variable with the name

‘tutorialName’ is defined in the controller and is attached to the scope. The command used is: 

$scope.tutorialName = “AngularJS”.

  • The variable i.e. ‘tutorialName’ can be called in the custom directive through the use of an expression. As the variable is defined in “DemoController”, it will be accessible. For our directive, “DemoController”,= will be the parent. 
  • The controller is referenced in a div tag that will become the parent div tag. The whole thing is to be carried out first so that the custom directive can access the variable ‘tutorialName’.
  • Finally, the custom directive which is “ng-guru” is attached to the div tag.
  • The successful execution of the code will generate the following output.

Output of the above code

Source

In the output, it can be observed that the tutorialName which is the scope variable is being used by the custom directive which is “ng-guru”.

Must Read: AngularJS for Web Development: Top 10 Compelling Reasons

Event Handling in a Directive

Handling of events such as mouse clicks or the clicks of buttons can be done from within a directive. The link function is used to handle the events. The directive is attached to the elements of the DOM in a page of HTML through the link function.

Syntax used for linking is: link: function ($scope, element, attrs).

Three parameters are accepted by the link function; scope, element, and the attributes.

Therefore,

  • A custom directive can be created for injecting the code in the main application of angular.
  • Members can be called by the custom directives. These members are defined within the object’s scope within a controller. Keywords used are ‘controller’, keyword controllerAs’, and the keyword ‘template’
  • Embedded functionality can be provided through the nesting of the directives.
  • Common code can be injected by making the directives re-usable.
  • Custom tags of HTML can be created through custom directives. These tags will have the functionality of their own and be defined as their requirement.
  • +DOM events can be handled from the directive.

Conclusion

Custom directives in angularjs are used for extending HTML functionality in angular. The creation of this type of custom directive is discussed in the article with an angular custom directive example. Overall a bit of the programming concept has been touched. However, if you desire to be an expert in software development, you should master your skills of programming applied in the software industries. Considering this, you can check the course Executive PG Programme in Software Development – Specialisation in Full Stack Development, offered by upGrad. The 13 months long program is designed for mid-level professionals within 21 to 45 years of age and who are awaiting their luck in the software development sector. With over 16 programming languages and tools, online sessions, and classes from leaders, the course will provide you with placement assurance in top industries. If you are interested, contact our team for further details. We will be at your assistance. 

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Enroll Now @ upGrad

0 replies on “How to Create a Custom Directive in AngularJS :Step by Step Explained”

×