AngularJS Directives

AngularJS Directives


Angularjs is an extension of Java script, maintained by Google, which helps to develop web applications. Angularjs provides a number of essential services that are extensible and work mutually. These services include data-binding, DOM manipulation, routing/view management, module loading, and many more.

Directive combines the Javascript and HTML into re-usable codes. Using directives is very easy, all we have to do is include the directive definitions in our HTML pages and then use the directive tags as we would for any regular HTML tag ().

Creating custom directives is the most exciting feature of AngularJS. Custom directives allow us to extend HTML with new tags and attributes. Directives can be re-used in multiple places within the projects.

In this blog we will discuss about a very basic, but important Angular directive.
We have taken ng-app as an example. Any time we see “ng-“we should assume that it is an Angular directive and an in-built directive. It is also possible for us to write custom ones.
There is another directive called “ng-model”. The ng-model acts as a back-end service by adding a property up in the memory called “scope”.

Use Case

The sample given below will explain how to create and use the custom directives in Angularjs app.

Setting up the App:

First we need to set up an Angularjs application & html.


 Setting up the App Controller:

Now we have created the App controller, it is used to pass the required values to the views using scope values.


 The Directive for email validation:

Now we need to create an AngularJS directive that will help us to validate multiple emails.



What we need to do:

  • angular.min.js

Here is a directive with complete email validation:
The email validation is done using directives and the error messages are displayed as shown in the images given below.

Result 1:

The email field with text area that allows multiple emails with comma ‘,’ separated by values is shown below.


Result 2:

Now it shows that the entered email is not a valid email (Error message “Please enter a valid Email address”), once we enter a correct email the error message is removed.

vj2Result 3:

The result given below has 2 emails (1st valid email, 2nd invalid email), so now we have to show the error message for the 2nd email as invalid email.

vj3The above sample shows email validation using custom directives in Angularjs.


  • There are some challenges while handling event bind and angular broadcast functionalities in Angularjs Directives, otherwise it really helps to fulfill our requirements for our apps.


  • This blog will really help us to simplify things while creating custom directives. We will be excited to create custom directives in AngularJS.


  • The AngularJS home page AngularJS by Google.

7145 Views 3 Views Today