For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentDirectives in AngularJS: How to Create? [with Examples]

Directives in AngularJS: How to Create? [with Examples]

Published
25th Apr, 2024
Views
view count loader
Read it in
11 Mins
In this article
    Directives in AngularJS: How to Create? [with Examples]

    Directives in angular are custom HTML attributes that tell it to change the style or behavior of the Document Object Model (DOM) elements. When we say that components are the building blocks of Angular applications, we are saying that directives are the building blocks of Angular applications. 

    To put it more simply, we can say that the directives in angular are instructions in the DOM. Directives specify how to place the components and the logic of Angular. Let us dive deep into what are the directives in AngularJS and learn more about its different types and their examples.

    What are Directives in Angular?

    We know that AngularJS extends the functionality of HTML. The use of directives in AngularJS is the main reason behind it. We use directives in AngularJS to convert a static page, an HTML page, into a dynamic page. Using a directive, we can do this without manually editing the code. For Document Object Model (DOM), directives in AngularJS are used to add specific behavior.

    Angular Directives

    The Syntax of AngularJS Directives

    Most of the directives in AngularJS start with ng as a prefix. ng stands for angular. But it does not always have to start with ng as a prefix. We can also use x- or data- as a prefix. 

    For example: 

    ng-init is a directive in AngularJS. It can also be written as x-ng-init or data-ng-init . All three forms have the same meaning. They are all used to perform the same task or functions. 

    We can also replace – by : or _ in the syntax. It will become ng:init or ng_init . All forms will have the same meaning and they will perform the same functions. You can refer to AngularJS live Project Training for more understanding of the concepts. 

    Example of AngularJS Directives

    Let’s see the example of the directive in AngularJS with different types of syntax. 

    Angular directive example: 

    <!DOCTYPE html> 
    <html > 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> 
    </head> 
    <body ng-app> 
    Name: <input type="text" ng-model="firstName" /> <br /> 
    data-ng-bind: <span data-ng-bind="firstName"></span><br /> 
    data-ng:bind: <span data-ng:bind="firstName"></span><br /> 
    data:ng:bind: <span data:ng:bind="firstName"></span><br /> 
    x:ng:bind: <span x:ng:bind="firstName"></span><br /> 
    ng:bind: <span ng:bind="firstName"></span><br /> 
    x-ng-bind: <span x-ng-bind="firstName"></span><br /> 
    x_ng_bind: <span x_ng_bind="firstName"></span><br /> 
    ng_bind: <span ng_bind="firstName"></span> 
    </body> 
    </html> 

    Output

    Name: 
    data-ng-bind: 
    data-ng:bind: 
    data:ng:bind: 
    x:ng:bind: 
    ng:bind: 
    x-ng-bind: 
    x_ng_bind: 
    ng_bind: 

    Now, when we write the input name in the given textbox, it will bind to all directives in the lines below and will be printed. Then the final output will look like this: 

    Name: John
    data-ng-bind: John 
    data-ng:bind: John 
    data:ng:bind: John 
    x:ng:bind: John 
    ng:bind: John 
    x-ng-bind: John 
    x_ng_bind: John 
    ng_bind: John 

    We can see the same name appears in every output. Whenever we change the name, it will get changed in every output directive. 

    Types of Directives

    There are two main types of directives in AngularJS.  

    1. Built-In directives - These directives in AngularJS are already predefined. We can directly use them for different functionalities in our application.
    2. Custom directives – Custom directives are made by the user. They are not predefined. We can define them based on their functionality.

    Let’s learn more about built-in directives and custom directives.  

    Built-In Directives

    Built-in directives are used to manage the elements like forms, lists, and styles of the application. To put it more simply, we can say that built-in directives are used to manage the elements that the user can see on the screen. 

    Based on the functions of directives, built-in directives can further be classified in three diverse types. 

    1. Components: Component directives in angular with the template. 
    2. Structural directives: These directives change the DOM layout by adding and removing DOM elements. 
    3. Attribute directives: These directives change the appearance or behavior of an element, component, or another directive. 

    Here are some examples of built-in directives in angularjs 

    1. ng-init 
    2. ng-bind 
    3. ng-model 
    4. ng-repeat 
    5. ng-if 
    6. ng-disable 
    7. ng-readonly 
    8. ng-class 
    9. ng-style 
    10. ng-for 
    11. ng-switch

    Custom Directives

    Custom directives are user-defined directives in AngularJS. These allow the user to use desired functions to extend the functionality of HTML. Also, new directives can be created to manipulate the HTML behavior. Thus, users can create directives in angular. 

    Users can use the directive function to define those custom directives, and it can replace the element for which it can be used. AngularJS has a lot of popular built-in directives; still, sometimes custom directives are required. 

    Let’s have an introduction to the ways to implement custom directives in AngularJS. 

    1. Element directives: It is activated when finding a matching HTML element in the HTML template. For example: <directive-name></directive-name> 
    2. Attribute directives: It is activated when finding a matching HTML attribute in the template. For example: <div directive-name></div> 
    3. CSS Class directive: It is activated when finding a matching CSS class in the template. For example: <div class=”directive-name: expression;”></div> 
    4. Comment directives: It is activated when finding a matching HTML comment. For example: <!-- Directive: directive-name expression; --> 

    We will see further in the article how to build these custom directives with angular custom directive examples. 

    AngularJS Directives List

    Now, we will learn which are the different types of directives in AngularJS and how they are used.  

    1. ng-app directive

    The ng-app directive defines the root element. It runs an AngularJS application and automatically initializes or loads the application when a web page containing an AngularJS application is loaded. It is also used to load various AngularJS modules in an AngularJS application. 

    Example: 

    <div ng-app=””>...</div> 

    2. ng-init directive

    ng-init directive initializes the data in the application of AngularJS. It defines the initial values of the data in the application. 

    Example: 

    <div ng-app=”” ng-init=”people=[{name:’Sam’,hobby:’painting’},{name:’John’,hobby:’reading’}]”>…</div> 

    3. ng-model directive

    Ng-model directive is used to define the variable to be used in the application. 

    Example: 

    <div ng-app = "">  
    <p>Enter your name: <input type = "text" ng-model = "name"></p>  
    </div>  

    4. ng-repeat directive

    This directive repeats the HTML element for each item in the collection. In the given an example we have iterated for the array of people. 

    Example: 

    <div ng-app=”"> 
    <p>List of people</p> 
    <ol> 
    <li ng-repeat = ”person in people”> 
    {{ ‘Name:’ + people.name + ‘Hobby:’ + people.hobby }} 
    </li> 
    </ol> 
    </div> 

    These are some of the most common directives in AngularJS. Below is the list of other directives and their description.

    DirectiveDescription
    ng-appIt defines the root element of an application.
    ng-repeatIt defines a template for each data in a collection.
    ng-mouseupIt specifies the behavior on mouseup events.
    ng-non-bindableIt specifies that no data binding can happen in this element, or it’s children.
    ng-mouseoverIt specifies behavior on mouseover events.
    ng-mouseoverIt specifies behavior on mouseover events.
    ng-mouseleaveIt specifies the behavior on mouseleave events.
    ng-mouseenterIt specifies the behavior on mouseenter events.
    ng-mousedownIt specifies behavior on mousedown events.
    ng-model-optionsIt specifies how updates in the model are done.
    ng-modelIt binds the value of HTML controls to application data.
    ng-formIt specifies an HTML form to inherit controls from.
    ng-disabledIt specifies if an element is disables or not.
    ng-valueIt specifies the value of an input element.
    ng-transcludeIt specifies a point to insert transcluded element.
    ng-switchIt specifies a condition that will be used to show/hide child elements.
    ng-submitIt specifies expressions to run on onsubmit events.
    ng-styleIt specifies the style attribute for an element.
    ng-srcsetIt specifies the srcset attribute for the <img> element.
    ng-srcIt specifies the src attribute for the <img> element.
    ng-showIt shows or hides html elements.
    ng-selectedIt specifies the selected attribute of an element.
    ng-requiredIt specifies the required attribute of an element.
    ng-readonlyIt specifies the readonly attribute of an element.
    ng-pluralizeIt specifies a message to display according to en-us localization rules.
    ng-pasteIt specifies the behavior on paste events.
    ng-optionsIt specifies <options> in a <select> list.
    ng-openIt specifies the open attribute of an element.
    ng-listIt converts text into a list (array).
    ng-keyupIt specifies the behavior of keyup events.
    ng-keypressIt specifies the behavior on keypress events.
    ng-keydownIt specifies a behavior on keydown events.
    ng-jqIt specifies that the application must use a library, like jQuery.
    ng-initIt defines initial values for an application.
    ng-includeIt includes html in an application.
    ng-ifIt removes the html element if a condition is false.
    ng-hrefIt specifies a URL for the <a> element.
    ng-hideIt hides or shows html elements.
    ng-focusIt specifies a behavior on focus events.
    ng-dblclickIt specifies a behavior on double-click events.
    ng-cutIt specifies the behavior of cut events.
    ng-cspIt changes the content security policy.
    ng-controllerIt defines the controller object for an application.
    ng-copyIt specifies the behavior of copy events.
    ng-cloakIt prevents flickering when your application is being loaded.
    ng-clickIt specifies an expression to evaluate when an element is being clicked.
    ng-classIt specifies CSS classes on html elements.
    ng-class-evenIt is same as ng-class, but will only take effect on even rows.
    ng-class-oddIt is same as ng-class, but will only take effect on odd rows.
    ng-checkedIt specifies if an element is checked or not.
    ng-blurIt specifies behavior on blur events.
    ng-changeIt specifies an expression to evaluate when content is being changed by the user.
    ng-bindIt binds the content of an html element to application data.
    ng-bind-templateIt specifies that the text content should be replaced with a template.
    ng-bind-htmlIt binds the inner HTML of an HTML element to application data, and also removes dangerous code from the html string.

    These directives are built-in, so they are easy to implement. You can check Web Design and Web Development Course Online for more practice and examples on this topic. 

    Scopes in Directives

    The scope has a particularly significant role in AngularJS. It acts as an intermediary between the Controller and the View (HTML) in AngularJS. Every angular directive scope object created by a controller or any other directive or service is inherited from the parent scope. 

    All directives have their angular directive scope. The scope uses directives to access data and methods inside a template and reference function. A directive never creates its own scope. It must be defined explicitly. By default, directives use their parent scope (from where it is called). 

    We can change the default angular directive scope using the scope property just like constraints, templates, etc. The value of the scope attribute defines how the scope of the directive will behave. The values are true and false. We can define the scope property in 3 ways. Here are different cases of using the scope in a directive: 

    • There is no value assigned to the scope or it is set as false 
    • The scope value is set as true 
    • Isolated scope 

    Let’s get to know more about the child scope and isolated scope. 

    1. Child Scope in Directives with Example

    When we declare scope: true at that time the DDO directive defines its own scope. This new scope is inherited from the scope of its parent controller. In this case, scope binding flow is only one way from the parent to the directive scope so any directive change is not reflected in the parent scope, but when we change the parent scope it is reflected in the directive scope  

    Angular directive example: 

    <div ng-app="test">
    <div ng-controller="parentController">
    <h2>Hey {{name}}</h2>
    <div>
    Change Form Header : <input type-="text" ng-model="name" />
    </div>
    <br/>
    <hr/>
    <div directive-with-true-scope></div>
    </div>
    </div> 
    <script>  
    var app = angular.module("test", []);
    app.controller("parentController", function($scope) {
    $scope.name = "Hitesh";
    });
    app.directive("directiveWithTrueScope", function() {
    return {
    restrict: "A",
    scope: true,
    template: "<div>Your name is : {{name}}</div>" +
    "Change your name : <input type='text' ng-model='name' />"
    };
    });</script> 

    In the above example, if we change the name in the header textbox, it is reflected in the directive scope, but when we change the directive scope it is not reflected in the parent scope if you want to reflect the parent scope, you have to use $parent for that.

    2. Isolated Scope in Directives with Example

    When we declare a scope: {} as an object in a DDO, then the directive creates a new isolated scope. And the scope does not inherit from the parent scope. So, if we want to access the values of the parent scope, we must declare it as a scope property in DDO, and this gets the property through directive attributes. 

    In isolated scope we can define scope property by using three prefixes.  

    • @ : One way binding  
    • = : Two-way binding  
    • & : Method binding 

    Example of isolated scope: 

    <div ng-app="app">
    <div class="parent" ng-controller="MainCtrl">
    <div class="line">
    Name inside parent scope is:<input type="text" ng-model="name" />
    </div>  
    <div class="line">
    Last name inside parent scope is:  
    <input type="text" ng-model="lastName" />
    </div>
    <br/>
    <hr/>
    <div class="directive" my-directive
    name="{{name}}"
    last-name="lastName"
    ></div>
    </div>
    </div> 
    <script>  
    var app = angular.module("app", []);
    app.controller("MainCtrl", function( $scope ){
    $scope.name = "Hitesh";
    $scope.lastName = "Jariwala";
    });
    app.directive("myDirective", function(){
    return {
    restrict: "EA",
    scope: {
    name: "@",
    lastName: "="
    },
    template: [
    "<div class='line'>",
    "Name using @ : <input type='text' ng-model='name' /><br/>",
    "</div><div class='line'>",
    "Last name using =: <input type='text' ng-model='lastName' /><br/></div>"].join("")  
    };
    });</script> 

    In the above example, if we change the first name in the parent scope so that it is reflected in the directive scope, but if we change the first name in the directive scope, then it will not be reflected in the parent scope due to one-way binding, just like if we change the last name in the parent scope, which is reflected in the scope of the directive and also if we change the last name in the scope of the directive, it will be reflected in the parent scope due to two-way binding just like we can pass parent scope method in directive scope and call from the directive.

    How to Create New AngularJS Directives [Step-by-Step]

    These are the custom directives that are made by the user. Previously we have learned some basics about custom directives. Here, we will get to know how to create directive angular. 

    How to Add Directives

    New directives are created by using the .directive function. To invoke a new directive, we have to make an HTML element that has the same tag name as the new directive. 

    While naming a directive, we must use a camel case name like myNewDirective , but while invoking it, we must use the name separated with – like my-new-directive. 

    Angular directive example: 

    <body ng-app=”myApp”> 
    <my-new-directive></my-new-directive> 
    <script> 
    var app = angular.module(“myApp”,[]); 
    App.directive(“myNewDirective”, function(){ 
    return{ 
    template : “<h1>Made by a directive! </h1>” 
    }; 
    }); 
    </script> 
    </body> 

    We can invoke a directive by using different methods. That are 

    1. Element name 
    2. Attribute 
    3. Class  
    4. Comment  

    Using all the methods of above, it will produce the same output. 

    We can add some restrictions to the directive. We can restrict the directive to be invoked by some of the methods only. 

    For example, by adding a restrict property with the value “C”, the directive can only be invoked by the class. 

    <script> 
    var app = angular.module(“myApp”,[]); 
    App.directive(“myNewDirective”, function(){ 
    return{ 
    restrict : “C” 
    template : “<h1>Made by a directive! </h1>” 
    }; 
    }); 
    </script> 

    There are some legal restrict values.  

    1. E – for Element name 
    2. A – for Attribute 
    3. C – for Class 
    4. M – for Comment 

    The default restrict value is EA. This means that both Element names and attribute names can invoke the directive.

    Getting Started with AngularJS Directive

    AngularJS directives are custom elements in HTML, such as an attribute, element name, comment, or CSS class. They tell AngularJS to attach a specified behavior to that DOM element, or even transform the DOM element and its children. Simply, when we create a directive, AngularJS will treat this element differently. 

    Step 1: Building a reusable component

    Directives in AngularJS can also be used to create a reusable component. Here is an example of a user box component. 

    UserBox.js 

    angular.module('simpleDirective', []) 
    .directive('userBox', function() {
    return {
    scope: {
    username: '=username',
    reputation: '=reputation'
    },
    templateUrl: '/path/to/app/directives/user-box.html'
    };
    }); 

    Controller.js 

    var myApp = angular.module('myApp', ['simpleDirective']);
    myApp.controller('Controller', function($scope) {
    $scope.user = "John Doe";
    $scope.rep = 1250;
    }); 

    MyPage.js 

    <html lang="en" ng-app="myApp">
    <head>
    <script src="/path/to/app/angular.min.js"></script>
    <script src="/path/to/app/controllers/Controller.js"></script>
    <script src="/path/to/app/directives/userBox.js"></script>
    </head>
    <body>
    <div ng-controller="Controller">
    <user-box username="user" reputation="rep"></user-box>
    </div>  
    </body>
    </html> 

    UserBox.html 

    <div>{{username}}</div>
    <div>{{reputation}} reputation</div> 

    Step 2: Installation or Setup

    Directives are built-in in the AngularJS library. The angular directive template is easy to use. Here angular directive template is given. A sample directive can be created as below: 

    angular.module('simpleDirective', [])
    .directive('helloData', function() {
    return {
    template: 'My name is {{data}}'
    };
    }); 

    It can be used in the controller given below: 

    angular.module('app', ['simpleDirective'])
    .controller('Controller', ['$scope', function($scope) {
    $scope.data = 'John';
    }]); 
    HTML code: 
    <div ng-controller="Controller">
    <div hello-data></div>
    </div> 

    Output: 

    My name is John 

    Step 3: Success/Error pop-up message using a simple link function

    The angular directive link function is used to manipulate DOM in custom directives. It takes three attributes as input in the sequence. These attributes are scope, element, and attribute. This angular directive link function is used to create success or error pop-up messages in the application. 

    Example of the link function creating success/error pop-up message: 

    In controller 
    $scope.message={
    text: "Saved Successfully",
    type: "SUCCESS"
    };   

    HTML 

    <user-info msg="message"> </user-info>
    JS 
    var mainApp = angular.module("mainApp", []);
    mainApp.directive('userInfo', function() {
    var directive = {};
    directive.restrict = 'E';
    directive.scope = {
    message : "=msg"
    },
    directive.link = function(scope, element, attributes) {
    if(scope.message.type==='SUCCESS')
    scope.message.text = 'SUCCESS: '+scope.message.text+' !';
    else if(scope.message.type==='ERROR')  
    scope.message.text = 'ERROR: '+scope.message.text+' !';
    else if(scope.message.type==='WARNING')  
    scope.message.text = 'WARNING: '+scope.message.text+' !'
    else if(scope.message.type==='INFO')  
    scope.message.text = 'INFO: '+scope.message.text+' !'
    element.on('click', function(event) {  
    $(this).fadeOut();  
    });
    },
    directive.template = '<div ng-class={{message.type}}>'+  
    '<div class="message-text">{{message.text}}<div>'+ '<div>';
     
    return directive;
    }); 

    Step 4: Your First Directive

    Now we will build a simple directive. A directive that will give a square of number 2. 

    Example: 

    <!DOCTYPE html>
    <html ng-app="exampleApp">
     
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script> 
    angular.module('exampleApp', [])
    .directive('myCalculator', function() {
    return {
    restrict: 'E',
    template: '<span> The square of 2 is: {{2*2}} </span>'
    };
    }); 
    </script>
    </head>
    <body>
    This is my first directive. <br>
    <my-calculator></my-calculator>
    </body>
    </html> 

    Output: 

    This is my first directive. 

    The square of 2 is: 4 

    Event Handling in Directives

    AngularJS directives consists of some directives which can be used to execute custom behaviors in DOM events. These behaviors include mouse click, double click, enter, key press, etc. 

    We can add AngularJS event listeners to our HTML elements by using the directives from below. 

    • ng-blur 
    • ng-change 
    • ng-click 
    • ng-copy 
    • ng-cut 
    • ng-dblclick 
    • ng-focus 
    • ng-keydown 
    • ng-keypress 
    • ng-keyup 
    • ng-mousedown 
    • ng-mouseenter 
    • ng-mouseleave 
    • ng-mousemove 
    • ng-mouseup 
    • ng-mouseover 
    • ng-paste 

    These are the event directives. Using these directives, we can run AngularJS functions which includes user events. 

    Note: An AngularJS event should not overwrite an HTML event, both events will be executed.  

    Looking to master Python? Discover the best course in Python that offers a unique learning experience. Unlock your coding potential today!

    Conclusion

    In this article, we learned about directives in AngularJS. The predefined directives in AngularJS are helpful in DOM manipulation. We can also create our own directives. Angularjs directives are used in updating data as soon as the changes are made. Thus, directives are a very important feature in the AngularJS library. For more clarification of concepts, you can go to the official documentation of AngularJS or you can visit the KnowledgeHut’s Angular Live Project Training.

    Frequently Asked Questions (FAQs)

    1How many types of directives are there in AngularJS?

    There are two sorts of directives in AngularJs: 

    • Built-in directive - These directives in AngularJS are predefined in a framework. We can utilise it straight away to add functionality to our app. 
    • Custom directive - Self-created directives are known as custom directives. These aren't really specified, but we can make our own definitions.
    2Why are directives used in Angular?

    Directives contain classes that provide elements in your Angular applications with more functionality. To control forms, lists, styles, and what users view, utilize Angular's built-in directives.

    3What is Directive in AngularJS with an example?

    Directives in AngularJS are HTML attributes with the prefix ng-. An AngularJS application is started with the ng-app directive. The ng-init directive is used to set up an application's data. The ng-model directive connects HTML controls (input, select, and textarea) to application data.

    4What are the three types of directives in Angular?

    The three types of directives in Angular are attribute directives, structural directives, and components.

    5What are the types of directives?

    There are four types of directives in Angular, 

    • Components directives. 
    • Structural directives. 
    • Attribute directives. 
    • Custom Directive.
    6What are the directives in Angular 4?

    Directives in Angular is a js class, which is declared as @directive.

    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon