Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 17 November, 2022

6.17K+ views
9 min read

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.

Check out our free courses to get an edge over the competition.

Registering a Module with that of a Directive

 Program for module registering to a directive 

Check out upGrad’s Java Bootcamp

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.

Check out upGrad’s Advanced Certification in Blockchain

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

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

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.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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.

Frequently Asked Questions (FAQs)

1. Can we create custom directive in AngularJS?

AngularJS is a powerful JavaScript framework for building single-page web applications. AngularJS is based on the Model-View-Controller (MVC) software architectural pattern. Angular provides the ability to create custom directives. A directive is basically a custom HTML attribute. It is a way to extend HTML vocabulary and modify the behavior of the DOM and your Angular application. There are two ways to create a custom directive in Angular using AfterViewInit and AfterContentInit.

2. What is the difference between link and compile in AngularJS?

AngularJS provides two methods to apply templates and styles to a view: compile and link. The compile method is called once during application start up before the application itself starts, and the link method is called once the application is started to run the specified section of code. The difference between Link and Compile will vary on the situation. The main point of Link is that it is used to bootstrap AngularJS with a static file, while Compile allow us to change the HTML.

3. What are the uses of AngularJs?

AngularJS is a JavaScript framework that helps us in development. AngularJS is a best fit for developing web applications. It is the programming model for developing single page applications. Actually, AngularJS extends HTML vocabulary for expressions, directives, controllers, filters, etc. If a developer uses AngularJS to develop a web application it is called AngularJS application. It is a good idea to use AngularJS for developing complex web applications. It works as an extension to HTML and add features to HTML. AngularJS applications are highly scalable and testable. It maintains the structure of HTML document and allows optional structure for defining the logic.