<script type="application/ld+json">
{
 "@context": "https://schema.org",
 "@type": "BlogPosting",
 "mainEntityOfPage": {
   "@type": "WebPage",
   "@id": "https://www.engati.com/blog/angular-js-components"
 },
 "headline": "How to create reusable components in AngularJS using Custom Directives",
 "image": "https://global-uploads.webflow.com/5ef788f07804fb7d78a4127a/608fe25446319e0efacb3e6b_How-to-create-reusable-components-in-AngularJS-using-Custom-Directives.png",  

"articleSection" : "Components that can be made dynamic",  

"articleBody" : [ "Visual components", "Functional components" ],
 "author": {
   "@type": "Organization",
   "name": "Engati Team"
 },  
 "publisher": {
   "@type": "Organization",
   "name": "Engati",
   "logo": {
     "@type": "ImageObject",
     "url": "https://global-uploads.webflow.com/5ef788f07804fb9e0aa41273/60950e66372af76cf098f036_engati%20logo_color.svg"
   }
 },
 "datePublished": "2021-02-10",
 "dateModified": "2021-05-31"
}
</script>

Tech Corner

How to create reusable components in AngularJS using Custom Directives

Engati Team
.
Feb 10
.
2-3 mins

Table of contents

Key takeawaysCollaboration platforms are essential to the new way of workingEmployees prefer engati over emailEmployees play a growing part in software purchasing decisionsThe future of work is collaborativeMethodology

It was one of those weekly meetings we used to have to discuss new UI/UX technologies or how we can go about making our codebase a bit less messy when one of my colleagues raised a concern about the number of directives we had created, which more or less served the same purpose. A few weeks later, he created a directive that could be reused and helped us replace an enormous number of lines of redundant code and save time that would have been spent in creating pretty much the same modals again. 

Taking the same example of creating confirmation modals, let’s dive into creating reusable components in AngularJS using custom directives. 


A simple confirmation modal can be replicated with reusable components—A much easier way to code!
A simple confirmation modal can be replicated with reusable components—A much easier way to code!


This is a simple confirmation modal box. These confirmation modals are mostly used before events that might lead to deletion or consequential actions. They pop up as a warning right before users confirm that the action they are trying to perform is not unintended. 

Such modals have a basic structure. In the example given above, we can identify seven components that can be made dynamic, four visual, and three functional. Let’s list them down. 

Components that can be made dynamic

Visual components

  • The modal title (Delete Confirmation)
  • The modal content (Are you sure you want to delete this post?)
  • The cancel action button text (No)
  • The confirm action button text (Yes)

Functional components

  • The action to be performed when the cancel action button is clicked
  • The action to be performed when the confirm action button is clicked
  • The ID of the modal to reference the respective modal

Now that we have our dynamic components well defined. Let’s dive straight into coding such a directive. Let’s first look at our javascript file, which will define our directive and its behavior. 

Coding these directives

confirmationModal.directive.js

angular.module(myWebsite).directive('confirmationModal', function () {
    return {
        restrict: "E",
        templateUrl: "app/shared/directives/modals/confirmationModal/confirmationModal.directive.html",
        scope: {
            title: '=',
            content: '=',
            cancelActionText: '=',
            confirmActionText: '=',
            cancelActionCallback: '&',
            confirmActionCallback: '&',
            modalId: '='
        }
    }
});

Here we create our directive and use isolated scope to take in the values for the seven dynamic components we mentioned above. If you have any confusion concerning how angular directives work, you can refer to the official documentation for the basics here. Let’s create the HTML file now, which is being passed in as the template URL in the code above. 

confirmationModal.directive.html

<div id="{{modalId}}" class="modal fade in" role="dialog" tabindex="-1"></div>
    <div  class="modal-dialog"></div >
        <div class="modal-content"></div>
            <div class="modal-header"></div>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3 class="modal-title" ng-bind="title"></h3>
           
            <div class="modal-body align-left"></div>
                <p ng-bind="content"></p>
           
            <div class="modal-footer"></div>
                <button type="button" class="cancel-button"  ="" ng-click="cancelActionCallback()" ng-bind="cancelActionText"> </button>
                <button type="button" class="confirm-button"  ="" ng-click="confirmActionCallback()" ng-bind="confirmActionText"></button>

This is the template of the reusable confirmation modal we have created. The values passed in from the controller to the directive will reflect here when the directive is actually rendered in the DOM. 

We are ready with our confirmation modal directive. Let’s put it into action by using it in one of our pages. 

home.html

Other code
.
.
.
<confirmation-modal title="'Confirm Delete'" content="'this is the content'" cancel-action-text="'cancel'" confirm-action-text="'confirm'" modal-id="'myModal'" cancel-action-callback="cancelDeleteCallback()" confirm-action-callback="confirmDeleteCallback()"></confirmation-modal>

Wherever we want a confirmation modal box, we can paste the code with its respective values. In this case, we have replicated the Delete Confirmation modal shown at the very start of the post. We are passing strings for the visual components and the modal-id attribute and function calls for the actions to be performed on the click of the No and Yes button respectively in this case. These functions will have to be defined in the controller currently bound to the HTML providing the scope (home.controller.js in this case). 

This is how a simple reusable component can be made with custom directives in AngularJS. Several other properties can also be passed in if the need arises. For example, we can take in the color class to be applied on the buttons or even take in the size of the modal, etc. Custom directives form a critical part of modularizing code in AngularJS and can be exploited in this way to avoid writing the same piece of code again and again and keeping common functionality in one place.

To conclude

We wanted to apply this knowledge with some of our own processes, which is why we made the process of duplicating and customizing nodes so simple. Once you've created a node for your chatbot, all you have to do is duplicate it, and change the values.

Sign up with Engati to explore our automation & Live Chat solutions!

Share
Share

Engati Team

At the forefront for digital customer experience, Engati helps you reimagine the customer journey through engagement-first solutions, spanning automation and live chat.

Andy is the Co-Founder and CIO of SwissCognitive - The Global AI Hub. He’s also the President of the Swiss IT Leadership Forum.

Andy is a digital enterprise leader and is transforming business strategies keeping the best interests of shareholders, customers, and employees in mind.

Follow him for your daily dose of AI news and thoughts on using AI to improve your business.

Catch our interview with Andy on AI in daily life

Continue Reading

How to create reusable components in AngularJS using Custom Directives

Engati Team
|
min read

It was one of those weekly meetings we used to have to discuss new UI/UX technologies or how we can go about making our codebase a bit less messy when one of my colleagues raised a concern about the number of directives we had created, which more or less served the same purpose. A few weeks later, he created a directive that could be reused and helped us replace an enormous number of lines of redundant code and save time that would have been spent in creating pretty much the same modals again. 

Taking the same example of creating confirmation modals, let’s dive into creating reusable components in AngularJS using custom directives. 


A simple confirmation modal can be replicated with reusable components—A much easier way to code!
A simple confirmation modal can be replicated with reusable components—A much easier way to code!


This is a simple confirmation modal box. These confirmation modals are mostly used before events that might lead to deletion or consequential actions. They pop up as a warning right before users confirm that the action they are trying to perform is not unintended. 

Such modals have a basic structure. In the example given above, we can identify seven components that can be made dynamic, four visual, and three functional. Let’s list them down. 

Components that can be made dynamic

Visual components

  • The modal title (Delete Confirmation)
  • The modal content (Are you sure you want to delete this post?)
  • The cancel action button text (No)
  • The confirm action button text (Yes)

Functional components

  • The action to be performed when the cancel action button is clicked
  • The action to be performed when the confirm action button is clicked
  • The ID of the modal to reference the respective modal

Now that we have our dynamic components well defined. Let’s dive straight into coding such a directive. Let’s first look at our javascript file, which will define our directive and its behavior. 

Coding these directives

confirmationModal.directive.js

angular.module(myWebsite).directive('confirmationModal', function () {
    return {
        restrict: "E",
        templateUrl: "app/shared/directives/modals/confirmationModal/confirmationModal.directive.html",
        scope: {
            title: '=',
            content: '=',
            cancelActionText: '=',
            confirmActionText: '=',
            cancelActionCallback: '&',
            confirmActionCallback: '&',
            modalId: '='
        }
    }
});

Here we create our directive and use isolated scope to take in the values for the seven dynamic components we mentioned above. If you have any confusion concerning how angular directives work, you can refer to the official documentation for the basics here. Let’s create the HTML file now, which is being passed in as the template URL in the code above. 

confirmationModal.directive.html

<div id="{{modalId}}" class="modal fade in" role="dialog" tabindex="-1"></div>
    <div  class="modal-dialog"></div >
        <div class="modal-content"></div>
            <div class="modal-header"></div>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3 class="modal-title" ng-bind="title"></h3>
           
            <div class="modal-body align-left"></div>
                <p ng-bind="content"></p>
           
            <div class="modal-footer"></div>
                <button type="button" class="cancel-button"  ="" ng-click="cancelActionCallback()" ng-bind="cancelActionText"> </button>
                <button type="button" class="confirm-button"  ="" ng-click="confirmActionCallback()" ng-bind="confirmActionText"></button>

This is the template of the reusable confirmation modal we have created. The values passed in from the controller to the directive will reflect here when the directive is actually rendered in the DOM. 

We are ready with our confirmation modal directive. Let’s put it into action by using it in one of our pages. 

home.html

Other code
.
.
.
<confirmation-modal title="'Confirm Delete'" content="'this is the content'" cancel-action-text="'cancel'" confirm-action-text="'confirm'" modal-id="'myModal'" cancel-action-callback="cancelDeleteCallback()" confirm-action-callback="confirmDeleteCallback()"></confirmation-modal>

Wherever we want a confirmation modal box, we can paste the code with its respective values. In this case, we have replicated the Delete Confirmation modal shown at the very start of the post. We are passing strings for the visual components and the modal-id attribute and function calls for the actions to be performed on the click of the No and Yes button respectively in this case. These functions will have to be defined in the controller currently bound to the HTML providing the scope (home.controller.js in this case). 

This is how a simple reusable component can be made with custom directives in AngularJS. Several other properties can also be passed in if the need arises. For example, we can take in the color class to be applied on the buttons or even take in the size of the modal, etc. Custom directives form a critical part of modularizing code in AngularJS and can be exploited in this way to avoid writing the same piece of code again and again and keeping common functionality in one place.

To conclude

We wanted to apply this knowledge with some of our own processes, which is why we made the process of duplicating and customizing nodes so simple. Once you've created a node for your chatbot, all you have to do is duplicate it, and change the values.

Sign up with Engati to explore our automation & Live Chat solutions!

Tags
No items found.
About Engati

Engati powers 45,000+ chatbot & live chat solutions in 50+ languages across the world.

We aim to empower you to create the best customer experiences you could imagine. 

So, are you ready to create unbelievably smooth experiences?

Check us out!