Overview Of AngularJS Directives

What is AngularJS?

AngularJS is a JavaScript Framework that is very powerful and its library is written in JavaScript. This framework is used to make single page applications. From this definition, you should get an idea that if we want to make a Single Page application, AngularJS is the answer as the most powerful JavaScript Framework. AngularJS extends the HTML with new attributes. AngularJS allows us to write applications in a clean Model-View-Controller way.

 
What is a Directive?

These are markers on a DOM that tell the compiler of AngularJs to attach a specific behavior to that DOM element.

AngularJS helps to extend HTML, using directives. AngularJS has some built in directives and it also lets us define our own directives. Basically, AngularJs directive is the extended HTML with prefix ng.

Some built in AngularJS Directives are given below.

  • ng-app- This initializes the AngularJS Application. It defines the root of Angular Application.
  • ng-init- This initializes the application's data.
  • ng-model- This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind- This directive binds the application data to View (HTML View).

After reading this, we must have a question in our mind about what the HTML compiler is. What does it mean to compile HTML? In AngularJS, compilation means attaching the directives to HTML elements to make them attractive in order to transform the elements.

Some AngularJS defined directives are given below.

Directive

Description

ng-app

Defines the root element of an application.

ng-bind

Binds the content of an HTML element to application data.

ng-bind-html

Binds the innerHTML of an HTML element to Application data and also removes dangerous code from the HTML string.

ng-bind-template

Specifies that the text content should be replaced with a template.

ng-blur

Specifies a behavior on blur events.

ng-change

Specifies an expression to evaluate when the content is being changed by the user.

ng-checked

Specifies if an element is checked or not.

ng-class

Specifies CSS classes on HTML elements.

ng-class-even

Same as ng-class, but will only take effect on even rows.

ng-class-odd

Same as ng-class, but will only take effect on odd rows.

ng-click

Specifies an expression to evaluate when an element is being clicked.

ng-controller

Defines the controller object for an application.

ng-copy

Specifies a behavior on copy events.

ng-cut

Specifies a behavior on cut events.

ng-dblclick

Specifies a behavior on double-click events.

ng-disabled

Specifies if an element is disabled or not.

ng-focus

Specifies a behavior on focus events.

ng-form

Specifies an HTML form to inherit the controls from.

ng-hide

Hides or shows HTML elements.

ng-href

Specifies a URL for the <a> element.

ng-if

Removes HTML element, if a condition is false.

ng-include

Includes HTML in an application.

ng-init

Defines initial values for an application.

ng-jq

Specifies that the application must use a library, like jQuery.

ng-keydown

Specifies a behavior on keydown events.

ng-keypress

Specifies a behavior on keypress events.

ng-keyup

Specifies a behavior on keyup events.

ng-list

Converts text into a list (array).

ng-maxlength

Specifies the maximum number of characters allowed in the input field.

ng-minlength

Specifies the minimum number of characters allowed in the input field.

ng-model

Binds the value of HTML controls to the application's data.

ng-model-options

Specifies how updates in the model are done.

ng-mousedown

Specifies a behavior on mousedown events.

ng-mouseenter

Specifies a behavior on mouseenter events.

ng-mouseleave

Specifies a behavior on mouseleave events.

ng-mousemove

Specifies a behavior on mousemove events.

ng-mouseover

Specifies a behavior on mouseover events.

ng-mouseup

Specifies a behavior on mouseup events.

ng-non-bindable

Specifies that no data binding can happen in this element, or its children.

ng-open

Specifies the open attribute of an element.

ng-options

Specifies <options> in a <select> list.

ng-paste

Specifies a behavior on paste events.

ng-pluralize

Specifies a message to display according to en-us localization rules.

ng-readonly

Specifies the readonly attribute of an element.

ng-repeat

Defines a template for each data in a collection.

ng-required

Specifies the required attribute of an element.

ng-selected

Specifies the selected attribute of an element.

ng-show

Shows or hides HTML elements.

ng-src

Specifies the src attribute for the <img> element.

ng-style

Specifies the style attribute for an element.

ng-submit

Specifies expressions to run on onsubmit events.

ng-switch

Specifies a condition that will be used to show/hide child elements.

ng-value

Specifies the value of an input element.

Examples of some directive used in examples,

  1. <div ng-app="">  
  2.     <p>FirstName: <input type="text" ng-model="fname"></p>  
  3.     <p ng-bind="fname"></p>  
  4. </div>   

ng-app directive is used in the div tag <div>. This makes this div tag the owner of this AngularJS application, which means this confirms that from this div, we are staring the Angular application and Angular features will be starting from this tag.

ng-model directive, in the input tag, binds the value of this input field to variable “fname.”This fname's value has been assigned by this ng-model. Whatever we type in this input field, the value will be assigned to fname variable. ng-bind directive now binds the value, which was assigned to the variable “fname”, to innerHtml of the <span> tag.

Now, if we run the application we will see the screen, as shown below.



We can also describe it by using Angular expression.

  1. <div ng-app="" ng-init="fName='Jasbeer'">  
  2.     <p>Name: <input type="text" ng-model=" fName "></p>  
  3.     <p>You wrote: {{ fName }}</p>  
  4. </div>   
Here, ng-app tells AngularJS that the owner of the Application is <div> tag. The {{ fName }} expression used in the example is the AngularJS data binding expression. It binds AngularJS expressions with AngularJS data. The expression {{ fName }} is connected with ng-model. Whatever n-model will have the value of fName variable, the expression {{ fName }} will get the same. If we run this program, we will get the output given below.



Here, we will see that the input box will be pre-filled with data “Jasbeer”, as we have provided in the directive ng-init. ng-init is used to initialize the data.

Let’s check one more directive ng-repeatng-repeat directive actually works like  thefor loop. It clones HTML elements once for each item in a collection.

Suppose we have an array, where we store student names. We will display the student names one by one in a collection. We will use ng-repeat for it. First, we will set the array with student names, using ng-init, which will initialize the student names in a variable, then we will use this variable in ng-repeat to repeat the items in a collection.

Suppose we have an array of student names.

  1. studentNames=['Jasbeer','Manpreet','Jatinder']   

We will initialize this, as shown below.

  1. ng-init="studentNames=['Jasbeer','Manpreet','Jatinder']"   
We will write the code to use ng-repeat, as shown below.
  1. <div ng-app="" ng-init="studentNames=['Jasbeer','Manpreet','Jatinder']">  
  2.     <ul>  
  3.         <li ng-repeat="x in studentNames">  
  4.             {{ x }}  
  5.         </li>  
  6.     </ul>  
  7. </div>  

Here, in the first line, we are initializing the studentNames, followed by repeating each item of the array, which was set in the variable studentNames.

There are many Angular directives and you can use them whenever needed. Now, we will see how can we create our own directive; i.e., a Custom Directive.

Creating Custom Directives

Before writing a directive, we must know how Angular’s HTML Compiler $compile determines when to use a given directive.

Element matches a directive when the directive is a part of its declaration. We can have

  1. <my-directive>{{fName}}</my-directive>   

Here, <my-directive> element matches the mydirective directive. $compile matches the directive, which is based on the element name, attributes, class names and comment.

We can create our own AngularJS directives. To create the directives, we first have to register our directives. The directives are registered on the modules. We will learn about the modules later.

We use module.directive API to register a directive. Directives are created, using .directive function. We should make HTML element with the same tag name as of directive to invoke the directive. The directives are always created, using camel case name like myDirective, but when we have to invoke it, we must use “-“ separated name like my directive.

Module.directive takes the normalized directive name, followed by the factory function and factory function returns an object with the different options to tell $compile that how the directive should behave when matched with HTML element.

Now, let’s create a directive in AngularJS.

Example
  1. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">    
  2. <head>    
  3.     <meta charset="utf-8" />    
  4.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>    
  5.     <title>Custom Angular Directives</title>    
  6. </head>    
  7. <body ng-app="myApp">    
  8.     
  9.     <my-directive></my-directive>    
  10.     
  11.     <script>    
  12.         var app = angular.module("myApp", []);    
  13.         app.directive("myDirective"function () {    
  14.             return {    
  15.                 template: "<h1>Created custom directive!</h1>"    
  16.             };    
  17.         });    
  18.     </script>    
  19.     
  20. </body>    
  21. </html>   

You can see we have initialized the directive by using the element name as my-directive here.

  1. <my-directive></my-directive>   

We can invoke the directive by using element name, attribute, class and comment. It will print what will be returned by the factory function by matching the directive name.

If we run this the output will be as shown below.


 

Restrict Custom Directives: 
 
We can make the directive invoke by element name, attribute, class or comment by restricting it. We have a restrict property. We can add that property with the value as “A”, “E”, “C” or “M”.

Restrict Values

  • A Attribute
  • E Element Name
  • C Class
  • M Comment.
We can use this, as shown below.
  1. //Restrict property for attribute  
  2. var app = angular.module("myApp", []);  
  3. app.directive("myDirective"function() {  
  4.     return {  
  5.         restrict: "A",  
  6.         template: "<h1>Created custom directive!</h1>"  
  7.     };  
  8. });  
Here, we have restricted it to an attribute only. The directive can only be invoked here by an attribute. For the reference, the command is given below.
  1. <div my-Directive ></div> 
These will produce the same result as displayed by using element name restriction.

Attribute

  1. <div my-Directive ></div>   

 If we run the code for restrict A, then we will get output like :

 
 
Class
  1. <div class="my-directive"></div>   

Let us see this with an example for class restrict.

code :
  1. <!DOCTYPE html>  
  2.   
  3. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  7.     <title>Custom Angular Directives</title>  
  8. </head>  
  9. <body ng-app="myApp">  
  10.   
  11.    
  12.     <div class="my-directive"></div>   
  13.   
  14.   
  15.     <script>  
  16.  var app = angular.module("myApp", []);  
  17.         app.directive("myDirective"function () {  
  18.             return {  
  19.                 restrict: "C",  
  20.                 template: "<h1>Created custom directive , Restricted Class!</h1>"  
  21.             };  
  22.         });  
  23. </script>  
  24.   
  25. </body>  
  26. </html>  
If we run this, we will get the output as :
 
 
Comment
  1. <!-- directive: my-directive -->   

For comment -- below is an example depicting directive for comment

Code:
  1. <!DOCTYPE html>  
  2.   
  3. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  7.     <title>Custom Angular Directives</title>  
  8. </head>  
  9. <body ng-app="myApp">  
  10.   
  11.      
  12.     <!-- directive: my-directive -->    
  13.   
  14.     <script>  
  15.   var app = angular.module("myApp", []);  
  16.         app.directive("myDirective"function () {  
  17.             return {  
  18.                 restrict: "M",  
  19.                 replace: true,  
  20.                 template: "<h1>Created custom directive , Restricted Comment!</h1>"  
  21.             };  
  22.         });  
  23.   
  24.     </script>  
  25.   
  26. </body>  
  27. </html>  
If we run this, we will get an output like below:
 
Element Name
 
  1. <my-directive></my-directive>  
If we want to restrict the directive for an element only, then we will use Restrict value : E, Below is an example for Element name
  1. <!DOCTYPE html>  
  2.   
  3. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  7.     <title>Custom Angular Directives</title>  
  8. </head>  
  9. <body ng-app="myApp">  
  10.   
  11.     <my-directive></my-directive>  
  12.   
  13.   
  14.     <script>  
  15.   var app = angular.module("myApp", []);  
  16.         app.directive("myDirective"function () {  
  17.             return {  
  18.                 restrict: "E",  
  19.                 template: "<h1>Created custom directive , Restricted Element name!</h1>"  
  20.             };  
  21.         });  
  22.   
  23.     </script>  
  24.   
  25. </body>  
  26. </html>  
 We will get the output as shown below:
 
 
By default, the value is EA, and it means for both element name and an attribute.
 
This was about the directives. In the next article, I will explain the Model and data-binding in AngularJS with the examples. Please provide feedback for this article.

Up Next
    Ebook Download
    View all
    Learn
    View all