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

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

25th Apr, 2024
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 > 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> 
    <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> 



    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. 


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


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


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

    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. 


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

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

    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>
    Change Form Header : <input type-="text" ng-model="name" />
    <div directive-with-true-scope></div>
    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' />"

    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 class="line">
    Last name inside parent scope is:  
    <input type="text" ng-model="lastName" />
    <div class="directive" my-directive
    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("")  

    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”> 
    var app = angular.module(“myApp”,[]); 
    App.directive(“myNewDirective”, function(){ 
    template : “<h1>Made by a directive! </h1>” 

    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. 

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

    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. 


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


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


    <html lang="en" ng-app="myApp">
    <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>
    <div ng-controller="Controller">
    <user-box username="user" reputation="rep"></user-box>


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


    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 
    text: "Saved Successfully",
    type: "SUCCESS"


    <user-info msg="message"> </user-info>
    var mainApp = angular.module("mainApp", []);
    mainApp.directive('userInfo', function() {
    var directive = {};
    directive.restrict = 'E';
    directive.scope = {
    message : "=msg"
    directive.link = function(scope, element, attributes) {
    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) {  
    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. 


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


    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!


    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.


    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.

    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon