Newsletter

How to Create Custom Directives in AngularJs

AngularJs » on Jan 5, 2016 { 2 Comments } By Sivateja

In this article I will describe how to create custom directives in the AngularJs. Custom angular directives are the markers of DOM element, I mean we will write the custom directives as normal HTML elements, attributes, CSS classes and as Comments in the view (in .html, .jsp page etc). Angular compiler will attach the specific behaviors to the DOM in place of these directives.

Custom-Directives-In-Angularjs

As I told, in Angularjs we can create custom directives in 4 different ways:

  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives

But how can we instruct angular to choose which type (Attribute, Element, CSS Clsss, Comment) of directive can be used in the page ? here we have a property called ‘restrict‘, by using this we can easily intimate angular how our custom directive is going to be displayed in the page.

Let me give a simple syntax and usage for all these four types:

Syntax

var app = angular.module('Java4sApp', []);

app.directive('java4sDirective', function() {
    return {
         restrict : 'E', // Using our directive as an Element

      // restrict : 'A'  // Using our directive as an Attribute
      // restrict : 'C'  // Using our directive as a Class
      // restrict : 'M'  // Using our directive as a Comment
 
         template : '<b>This is element directive</b>'
    };
});

In View (.html/.jsp)

<java4sDirective></java4sDirective>     // Using custom directive as an Element

/*
    // Using custom directive as an Attribute  
       <div java4sDirective></div>          

    // Using custom directive as a Class 
       <div class="java4sDirective"></div>  

    // Using custom directive as a Comment 
       <!-- directive: java4sDirective -->  
*/

Explanation

  • In the syntax, I have created my own directive with name java4sDirective [ line number 3 ] and a return function [line number 4], having two properties, restrict & template
  • restrict – this property will accept four values E,A,C,M. In the current syntax I am using ‘E‘ means I am going to create/use my custom directive as an element in the HTML (in view line number 1<java4sDirective></java4sDirective>)

    restrict : ‘E‘ > If we would like to use our custom directive as an Element
    restrict : ‘A‘ > If we would like to use our custom directive as a Attribute
    restrict : ‘C‘ > If we would like to use our custom directive as Class
    restrict : ‘M‘ > If we would like to use our custom directive as a Comment

  • template – this property will accept the plain/HTML content to be displayed in our page in place of our custom directive

This is how we can create a simple custom directive in angularjs, but its not over, still there is somthing to learn regarding angular custom directive 🙂 In the above syntax, the return function having two properties called ‘restrict‘ and ‘template‘, apart from these we also have few other properties templateUrl, compile & link functions, controller, firstly I will explain about templateURL.

Using templateUrl

We already know about template property, this property will accept one or two or three or some lines of Text/HTML 🙂 and displayed in our page, but what if you want to display lines and lines of Text/HTML content ? Actually template property can do that but we need to write lines of text/html code in the JavaScript (in the return function) but that’s not a good deal.

Now templateUrl comes into picture, just put all your HTML in a separate file, and just specify that URL to templateUrl property, simply angularjs will load your HTML code from that file.

Syntax

var app = angular.module('Java4sApp', []);

app.directive('java4sDirective', function() {
    return {
        restrict : 'E',
        templateUrl : "/project-source-templates/java4s-sample-template.html";
    };
});

In View (.html/.jsp)

<java4sDirective></java4sDirective>

Angular now will load HTML template/content from the URL you have given to templateUrl and that’s it.

Complete Example

index.html

<html ng-app='Java4sApp'>
<head>
<title>Custom Directives In the Angular Js _ Java4s</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> 

<script> 
    var myapp = angular.module('Java4sApp', []); 
    myapp.directive("java4sCustomDir",function(){ 
          return ({               
                 restrict : 'C',
               //template: 'I am text from template', 
                 templateUrl: '<your file path>/custDirHtml.html'
          }); 
    });
</script>
</head>
<body>
     
     <div class="java4sCustomDir"></div>

</body>
</html>

custDirHtml.html

I am from external HTML file.

Output

Just open index.html in a browser and you will see…

I am from external HTML file.

Explanation

In the index.html

  • line number 8 > created custom directive with name ‘java4sCustomDir’
  • line number 10 > restrict : ‘C’ means, we are going to use our custom directive as a class in the view (<div class=”java4sCustomDir”></div>)
  • line number 12 > templateUrl: ‘<…..>/custDirHtml.html’ means, content in custDirHtml.html will be fetched and stored in teamplateUrl property and will be displayed in place of our directive (line number 19), that’s it 🙂

Just forget about compile, link functions and directive controller for now, I will explain about them in the coming article by taking an example.

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
- Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

2 Responses to “How to Create Custom Directives in AngularJs”
  1. Rajesh says:

    Need more tutorials on Angular JS.

  2. Naga says:

    To each example please provide download option also for practice.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2018 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.