Open In App

What are Directives in AngularJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS directives are extended HTML attributes having the prefix ng-. Directives are markers on the DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. During compilation, the HTML compiler traverses the DOM matching directives against the DOM elements. When we say “compilation” for AngularJS, we mean attaching directives to HTML to make it interactive and when we say an element matching a directive, we mean when a directive is specified in its declaration. In AngularJS, directives help in making the code modular with every directive having a separate functionality and being independent of the other directives. This helps to make the code more organized. 

Syntax:

<div ng-app=""></div>

Most directives start with ng- prefix, ng here stands for Angular. A directive can also start with x- or data-. The hyphen(-) can be replaced with a colon(:) or underscore (_) or both. For example, ng-init can be written as data-ng-init or x-ng-init or data:ng:init or x:ng:init, etc. The best practice is to use the dash-delimited format.

In AngularJS there is a set of built-in directives like ng-app, ng-init, ng-model, and ng-repeat. In addition to this, we can also create your own directives known as custom directives. Here, we will discuss some of the built-in directives in detail.

  • ng-app: The ng-app directive is used to start an AngularJS application. It is also called the root element of the application. When an AngularJS application loads ng-app automatically bootstraps or initializes the application.

Syntax:

<div ng-app=""></div>
  • ng-init: The ng-init directive is used to initialize the AngularJS application data by assigning values to variables.

Syntax:

<div ng-init="fruits=['Apple','Banana','Orange','Mango']"></div>
  • ng-model: The ng-model directive defines the model/variable to be used in the AngularJS application. This directive is used for two-way data binding in AngularJS.

Syntax:

<input ng-model="name"></input>
  • ng-bind: The ng-bind directive is used for on-way binding in AngularJS applications. This means the value of the content in the element where the ng-bind directive is specified changes whenever the value of the expression in the ng-bind directive changes.

Syntax:

<input ng-bind="name"></input>
  • ng-controller: This directive is used to add a controller to the AngularJS application. A controller acts as the glue between the model and the view. They take input from the view, process it, and return the output to be displayed to the user.

Syntax:

<div ng-controller="myCtrl"></div>

Example 1: In this example, we have used the above-mentioned directives.

HTML




<html>
  
<head>
    <title>AngularJS Directive</title>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <div ng-controller="myCtrl" 
         ng-init="title='Program to calculate factorial of a number'">
        <h1>{{title}}</h1>
        <form>
            <label>Enter a number:</label>
            <input type="text" 
                   ng-model="num">
            <br>
            <input type="submit" 
                   ng-click="calculate()">
            <p ng-bind="ans"></p>
  
        </form>
    </div>
    <script type="text/javascript">
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function($scope) {
            $scope.calculate = function() {
                $scope.fact = 1;
                for(var i = $scope.num; i >= 1; i--) {
                    $scope.fact = $scope.fact * i;
                }
                $scope.ans = $scope.fact;
            }
        })
    </script>
</body>
</html>


Explanation: In the above example, we have used the ‘ng-app’ directive to initialize the application, the ‘ng-controller’ directive to mention the controller being used, and the ‘ng-init’ directive to initialize the value of the variable of ‘title’. In the<input> tag we have used ‘ng-model’ for two-way data binding so that whenever the user enters a number it is updated o the view as well as in the model and vice versa. For the submit button we have used the ‘ng-click’ directive to specify the function to be called on clicking the button. In the <p> tag we have used the ‘ng-bind’ directive to bind the value of the variable ‘ans‘.

Output: The user enters a number and clicks on the submit button, and the factorial of the number is calculated and displayed.

 

Custom Directive: We can also create your own directive or a custom directive. A custom directive is a user-defined directive. The custom directive is created with the help of the .directive function and replaces the element for which it is used. The function has a property named ‘template’ where you can define the template of your directive.

Approach: Create a module for the application. It is mandatory as we will create the custom directive using this module. Then, create a custom directive using the .directive function. Inside the template parameter, specify what is to be displayed when the custom directive is called. After this, call the custom directive by specifying it in an HTML element.

app.directive("ngExample",function(){
return{
template: ‘<div>GeeksforGeeks</div>
}
});

Points to be noted while creating the Custom Directive:

  • The name of the custom directive should start with ‘ng’.
  • While defining the custom directive, use a camel case like ‘ngExample’ whereas while invoking it uses a hyphen like ‘ng-example’.
  • A directive can be invoked using an element name, attribute, class, or comment.

Element name:

ng-example><ng-example>
  • Attribute:
<div ng-example></div>
  • Class:
<div class="ng-directive"></div>
  • Comment:
<!-- directive: ng-example -- > 

Example 2: This example describes the creation of a custom directive.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>AngularJS Custom Directive</title>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <div>
        <div ng-example=""></div>
    </div>
    <script type="text/javascript">
        var app = angular.module("myApp", []);
        app.directive("ngExample", function() {
            return {
                template: "<div>GeeksforGeeks</div>"
            }
        });
    </script>
</body>
</html>


Explanation: In the above example, we have created a module named “myApp”. Using the module we have created a custom directive named “ngExample”. In the <div> tag we have specified the directive as “ng-example”. When we specify this directive the value defined for the template will be injected in this <div> tag thus printing “GeeksforGeeks”.

Output:

 

Example 3: This example describes the Custom directive and Scope. When we create a custom directive in a controller, by default it has the access to the scope object of that controller. This example shows how a custom directive can use the scope of the parent controller. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        AngularJS Custom Directive & Scope
    </title>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <div ng-controller="myCtrl">
        <div ng-example=""></div>
    </div>
    <script type="text/javascript">
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function($scope) {
            $scope.title = "GeeksforGeeks",
                $scope.description = {
                    "topic": "AngularJS Custom directive",
                    "topicdescription": 
"Custom directives are user defined directives"
+ " used to extend HTML functionality."
                }
        })
        app.directive("ngExample", function() {
            return {
                template: 
"<div><h1>{{title}}</h1><p style='font-size:25px'>{{description.topic}}</p>
<p style='font-size:25px'>{{description.topicdescription}}</div>"
            }
        });
    </script>
</body>
</html>


Explanation: In the above example we have created a module named “myApp”, a controller named “myCtrl” and a custom directive named “ngExample”. In the controller, we have attached properties named “title”, and “description” to the scope. We have accessed these properties in the directive with the help of the expressions. We have used two <div> tags. In the parent <div> tag, we have specified the controller using the “ng-controller” directive. In the other <div> tag we have specified the custom directive as “ng-example”.

Output:

 

Example 4: This example describes the Custom directive and Controller. If we don’t create the custom directive inside the controller the custom directive can still access the controller’s members without using the scope object. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        AngularJS Custom Directive & Controller
    </title>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <div ng-controller="myCtrl">
        <div ng-example=""></div>
    </div>
    <script type="text/javascript">
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function() {
            this.title = "GeeksforGeeks";
            this.courses = 
                    ["Live Courses", 
                     "Self-Paced Courses", 
                     "School Courses"];
            this.tutorials = 
                    ["Practice DS and Algo.", 
                     "Algorithms", 
                     "Data Structure", 
                     "Software Designs", 
                     "CS Subjects", ];
        });
        app.directive("ngExample", function() {
            return {
                controller: "myCtrl",
                controllerAs: "ctrl",
                template:
"<div><h1>{{ctrl.title}}</h1>
<p>Courses</p>
<ul ng-repeat='x in ctrl.courses'><li>{{x}}</li></ul><br>
<p>Tutorials</p>
<ul ng-repeat='x in ctrl.tutorials'><li>{{x}}</li></ul></div>"
            }
        });
    </script>
</body>
</html>


Explanation: In the above example we have created a module named “myApp”, a controller named “myCtrl” and a custom directive named “ngExample”. A point to note here is that we have not attached the properties to the scope instead we have attached them to the controller. In the custom directive, we have mentioned the controller name and created a reference to the controller named “ctrl”. In the template we have used the properties of the controller as “{{ctrl.title}}”, “{{ctrl.courses}}” etc. We have used two <div> tags. In the parent <div> tag, we have specified the controller using the “ng-controller” directive. In the other <div> tag we have specified the custom directive as “ng-example”.

Output:

Example 4



Last Updated : 03 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads