🎉Celebrating 25 Years of Tech Excellence and Trust - Learn More

Web Development
Published: Aug 10, 2023

What is Directives in AngularJS? And How to Build a New One?

Verified
Verified Expert in Engineering
Rahul Buddha is a highly accomplished Technical Innovator, holding 9 years of expertise in market-leading technologies such as Node.js, Vue.js, AWS Services, and so on.
Guide to AngularJS Directives

Quick Overview: Angular has always remained in good books, and it still is, as it's a pretty popular web framework for frontend development, providing many features. And one such efficient and essential feature is – directives in AngularJS. These attributes help extend the HTML capabilities. And there's much more! Hence, to know what is Angularjs directives and their aspects, read the blog. Hope you enjoy!

Are you a software developer? Or probably a tech freak like me? Then I'm pretty sure you must have some idea about AngularJS. Jogging our memories a little bit - AngularJS is an open-source, JavaScript frontend framework developers majorly use to build single-page web applications (SPAs). It acquires the utmost capabilities to change static HTML to dynamic HTML. Organizations opt for AngularJS development services due to their prime features, like Dependency Injection, Filters, Routers, Templates, Directives, Services, Controllers, two-way data binding, etc. In essence, as per Web Tech Survey, currently, 709,731 websites are using Angularjs.

Although, today, we're not here to learn the ABCs of AngularJS but to learn a related tech buzzword. So, here I am with another blog and another tech-oriented subject related to the essential feature of Angularjs – directives in Angularjs.

Wondering what is AngularJs directive?

AngularJS is a popular web framework for frontend development supporting Model-View-Controller (MVC) based architecture, which helps extend the HTML with new attributes. And these attributes are called directives in Angularjs. Furthermore, you must understand that directives in AngularJS are markers on DOM (Document Object Model) elements, helping to extend HTML, for instance, element name, attribute name, comment, or CSS (Cascading Style Sheet) class. This was the brief answer to the question - what is Angularjs directive? There's still a good long story.

So, stick with me and allow me to give you a little tour of our subject – directives in AngularJS. In this blog, we'll learn about distinct aspects of Angularjs directives. Since directives are a bit of a technical topic, it will require a good knowledge of its background (Angular JS and Angular). Hence, I suggest you go through our blog – Angular vs AngularJS – and gain some background knowledge.

Tighten your seat belts and ride along with me!

Team Up with Top AngularJS Development Company to Build Dynamic Web and Mobile Apps

Consult us NOW
On This Page
  1. What is AngularJS directives?
  2. Why Use Directive in AngularJS?
  3. Syntax of AngularJS Directives
  4. Best AngularJS Directive Example
  5. AngularJS Directive Types
  6. AngularJS Directives Scope
  7. How to Build New AngularJS Directive?
  8. AngularJS Directives: Getting Started
  9. Conclusion

What is AngularJS directives?

Angularjs directives are the new attributes that help extend the existing HTML capabilities and seamless web page development using core JavaScript. Moreover, it enables you to write your custom tags and map them into existing HTML. Directives in AngularJS provide developers more freedom and make them experience great flexibility in building and employing custom elements in web apps as per your needs. Also, you can create directives in Angularjs (yes, you can have your directives too).

Directives are one of the most valuable and efficient features in AngularJS. Angularjs directives are used in the DOM element as markers, which notify AngularJS to attach a unique behavior to that DOM element or even modify the DOM element with its children. In simple terms, AngularJS acquires a set of inbuilt directives that provides application functionality. Moreover, you can also define directives in Angular JS in distinct functions like - Comment, Class, Attribute, and Element name. Thus, the AngularJS compiler connects the specific behavior to that element (what we read above).

All in all, directives in Angularjs are a gem of a feature used by top AngularJS frameworks for web development. Also note that Angularjs directives extend their attributes with a prefix, i.e., ng-. And following are some components of directives in Angularjs:

  • ng-app: This directive informs the compiler about the AngularJS app.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script>
<body>
<div ng-app = "">
<! -- main code -->
</div>
</body>
</html>

  • ng-init: This directive helps initialize the data for the Angularjs app.
  • ng-model: This directive helps define the model and enables sending data in AngularJS.
<body>
<div ng-app = "">
<p> Enter: <input type="text" ng-model = "input"> </p>
</div>
</body>

  • ng-repeat: This directive helps repeat the HTML elements for each item in the array.

Now, that's all about – what is AngularJS directive? Coming to another aspect – its importance.

Why Use Directives in AngularJS?

We've discussed the 'what' part, and now comes the 'why.' Why use directives in Angularjs? Following are some of the important reasons why one should use directives in AngularJS:

  • It provides developers with excellent support to build custom directives for various elements.
  • When a matching or similar element is in front, it activates a directive.
  • Directives in Angularjs give better power to HTML with the help of new syntax.
  • Like component classes, directive classes can employ life-cycle hooks to impact their behavior and configuration.

Experience Seamless Integration of Next-Gen Technologies with Help of Expert Angular Minds

Opt Best AngularJS Services

Syntax of AngularJS Directives

Most of the directives in AngularJS begin with the prefix ng. And here, the ng means angular. However, note - it's not always necessary to start with ng as a prefix. AngularJS developers also use x- or data- as prefixes.

Umm, let me explain this with an example:

So, ng-bind is a directive, also written as data-ng-bind. OR

ng-bind is a directive that can also be written as x-ng-bind.

So, the meaning of ng-bind or x-ng-bind, or data-ng-bind is similar. Genius! Moreover, AngularJS developers use them to carry out the same functionality. Also, you can replace them – in the syntax of the Angularjs directive with : or _

And how?

See, ng-bind is a directive you can also write as ng:bind. OR

ng-bind is a directive that you can also write as ng-bind.

The meaning of ng:bind or ng-bind, or ng_bind is similar. As well as that they are all used to perform similar functionality.

Well, I'm pretty sure you understand the Angularjs directives syntax and how you can write it.

Learning something with the help of an example makes the process seamless and exciting too. Therefore, in the next section, we'll go through an AngularJS directive example (the best way to grasp directives in AngularJS).

Best AngularJS Directive Example

Here's one of the best and easiest AngularJS directive examples you can follow for better understanding. This AngularJS directive example presents syntax variation through the code.

<!DOCTYPE html>
<html >
<head>
<script src="[https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"](https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js%22)></script>
</head>
<body ng-app>
Guide Name is: <input type="text" ng-model="name" /> <br />
data-ng-bind: <span data-ng-bind="name"></span><br />
data-ng:bind: <span data-ng:bind="name"></span><br />
data:ng:bind: <span data:ng:bind="name"></span><br />
x:ng:bind: <span x:ng:bind="name"></span><br />
ng:bind: <span ng:bind="name"></span><br />
x-ng-bind: <span x-ng-bind="name"></span><br />
x_ng_bind: <span x_ng_bind="name"></span><br />
ng_bind: <span ng_bind="name"></span>
</body>
</html>

The output you'll receive:

Guide Name is:
data-ng-bind:
data-ng:bind:
data:ng:bind:
x:ng:bind:
ng:bind:
x-ng-bind:
x_ng_bind:
ng_bind:

Now, whenever you write anything within the textbox, it will be displayed as equivalent to each directive where we want to print the name.

Guide Name is: Data Flair (#Data Flair will appear in a textbox)

data-ng-bind: Data Flair

data-ng:bind: Data Flair

data:ng:bind: Data Flair

x:ng:bind: Data Flair

ng:bind: Data Flair

x-ng-bind: Data Flair

x_ng_bind: Data Flair

ng_bind: Data Flair

And whenever you need to modify the text within the textbox, it will also change in the below places.

Moving ahead, it's imperative to understand Angular directives types, and in the next section, we will do the same.

Hire Best-of-All AngularJS Developers to Help Craft Dynamic Web Applications

Let Experts Help

Important Note: Whether it be any version of Angular - Angular 16, Angular 17 or AngularJS, they all use the same Angular directives types. However, how they use it makes the only difference. Okay, more straightforwardly, Angular acquires standard directives, and AngularJS consists of a pack of them. And this is why I will use the term Angular at various places in the blog (as an umbrella term).

AngularJS Directive Types

There are two main types of directives in AngularJS. Let's see which:

  • Built-In Directives in Angular - These Angular built-in directives are already predefined. You can directly utilize them for distinct functionalities in your application.

  • Custom Directives in Angular – Users design the custom directives in Angular. No, they aren't predefined. Although, you can define them as per their functionality.

Fascinating, right? Let's learn a bit more in detail about these built-in and custom directives in Angular.

1. Built-In Angular Directives - Frontend developers use Angular built-in directives to manage different elements like styles, lists, and app forms. Simply put, you can use Angular built-in directives to control other elements visible to the user on the screen.

Based on the directives functionalities, you can classify Angular built-in directives into three types: component directives in Angular, structural directives in Angular, and attribute directives in Angular.

  • Component Directives in Angular - The component directives in Angular consist of the template.
  • Structural Directives in Angular - These structural directives in Angular helps modify the DOM layout by adding and subtracting DOM elements.
  • Attribute Directives in Angular - These attribute directives in Angular help change the behavior and appearance of another directive or an element or component.

Following are some examples of built-in AngularJS directives list:

Built-in Directives of AngularJS

  • ng-init
  • ng-disable
  • ng-switch
  • ng-style
  • ng-readonly
  • ng-repeat
  • ng-model
  • ng-bind
  • ng-if
  • ng-class
  • ng-for

2. Custom Angular Directives - Custom directives in Angular are user-defined directives in AngularJS. These enable the users to utilize certain functions to extend their HTML functionalities. Also, frontend developers can easily create new custom Angular directives to handle the HTML behavior.

Users can easily use the directive function to define these custom directives in Angular, and it can also substitute the element for which it can be utilized. AngularJS consists of several popular built-in directives, yet sometimes you'll need custom directives in Angular.

So, let's get familiar with the approaches; you can implement custom directives in AngularJS.

Custom Angular Directives

  • Element Directives in Angular - After finding a similar HTML element in the HTML template, it gets activated. For instance, <directive-name></directive-name>
  • Attribute Directives in Angular - It gets activated when searching for a similar HTML attribute in the template. For instance, <div directive-name></div>
  • CSS Class Directive in Angular - It is activated when searching for a similar CSS class in the template. For instance, <div class=”directive-name: expression;”></div>
  • Comment Directives in Angular - It gets activated when looking for a similar HTML comment. For instance, <!-- Directive: directive-name expression; -->

Therefore, these were the two crucial Angular directives types.

Coming to yet another essential part, discussing Angularjs directive scope. Why wait, then?

Come on!

AngularJS Directives Scope

The AngularJS directive scope has a critical part to play. It is an intermediary between the View (HTML part) and the controller in AngularJS. Every Angular js directive scope object is developed by a Controller or any service or directive inherited from the parent scope.

All directives consist of their angularJS directive scope. And why? Since the scope utilizes the directives to access data and approaches inside a reference and template function. Always remember a directive can never build its scope. It must be explicitly defined. So, by default, directives must use their parent scope (from where it is called).

You can modify the default Angular JS directive scope using the scope characteristics, like, templates, constraints, etc. Therefore, the scope attribute's value determines the directive scope's behavior. The values are either true or false. Hence, you can define the Angularjs direct scope property in 3 different approaches. The following are the scope cases:

  • When there's no value assigned to the scope, or it is set as false
  • The scope value is set as true
  • Isolated scope

Here's the most crucial part of our blog – to create new directives in Angularjs. Creating a directive in Angular isn't an easy-peasy job; it requires technical knowledge, basic know-how of AngularJS concepts, and a bit of understanding of top Angularjs tools. However, I've made your work a little easier and discussed the steps in a bit easy way to create directives in Angular.

Deliver the Best User Experiences Combining Your Ideas and Radixweb's Frontend Expertise

Choose Frontend Development

How to Build New AngularJS Directive?

These are the custom directives in AngularJS made by the user. We have already gone through the basics of custom directives in AngularJS. Therefore, here we'll learn how to create directives in Angular.

First, Add Directives

You can build new directives in Angularjs by using the .directive function. And to call down a new directive, you'll have to make an HTML element with the same tag name as the new directive. And make sure while naming the directive, make sure to use the camel case name, for instance, myNewDirective, but while calling it, use the name divided with – like, my-new-directive.

Let's see the Angular custom directive example:

<body ng-app=”myApp”>
<my-new-directive></my-new-directive>
<script>
var app = angular.module(“myApp”,[]);
App.directive(“myNewDirective”, function(){
return{
template : “<h1>Made by a directive! </h1>”
};
});
</script>
</body>

You can invoke Angularjs directives by using distinct approaches, including:

  1. Element name
  2. Attribute
  3. Class
  4. Comment

Using all the above approaches will eventually generate the same output (so it's your choice).

You can also add some restrictions to the directive. Okay, in simple terms, you can restrict the directive to be called out by only some methods. For instance, you can add a restricted property with the value "C," the class can only call the directive.

So, here are some legally restricted values you can use.

  1. E – for Element name
  2. A – for Attribute
  3. C – for Class
  4. M – for Comment
<script>
var app = angular.module(“myApp”,[]);
App.directive(“myNewDirective”, function(){
return{
restrict : "C"
template : “<h1>Made by a directive! </h1>”
};
});
</script>

AngularJS Directives: Getting Started

Let's now get it going and create directive in Angular.

Step.1: Creating a Reusable Component

Directives in AngularJS can very well be used to build a reusable component. Here is a user box component example:

UserBox.js

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

Controller.js

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

MyPage.js

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

UserBox.html

<div>{{username}}</div>
<div>{{reputation}} reputation</div>

Step.2: Installation/Setup

Some directives are built-in in the AngularJS library. The Angular directive template is quite easy to utilize. Here, an Angular directive template is already given. So, a sample directive can be built as shown below:

angular.module('simpleDirective', [])
.directive('helloData', function() {
return {
template: 'Welcome to {{data}}'
};
});

It can be used in the controller given below:

angular.module('app', ['simpleDirective'])
.controller('Controller', ['$scope', function($scope) {
$scope.data = 'Radixweb';
}]);
HTML code:
<div ng-controller="Controller">
<div hello-data></div>
</div>

Output: Welcome to Radixweb

Step.3: Success/Error Pop-Up Notification Using a Simple Link Function

The Angular directive link function handles DOM in custom directives in Angularjs. It requires three attributes as input in a progressive manner. These attributes are - scope, element, and attribute. This Angular directive link function is then used to build success or error pop-up notifications in the app.

Example of the link function building success/error pop-up message:

In controller
$scope.message={
text: "Saved Successfully",
type: "SUCCESS"
};

HTML

<user-info msg="message"> </user-info>

JS
var mainApp = angular.module("mainApp", []);
mainApp.directive('userInfo', function() {
var directive = {};
directive.restrict = 'E';
directive.scope = {
message : "=msg"
},
directive.link = function(scope, element, attributes) {
if(scope.message.type==='SUCCESS')
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) {
$(this).fadeOut();
});
},
directive.template = '<div ng-class={{message.type}}>'+
'<div class="message-text">{{message.text}}<div>'+ '<div>';
return directive;
});

Step.4: Voila! Your First Directive is Ready

Now we will build a simple directive to give a square of the number 3.

Example:

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

Output:

This is my first directive.

The square of 3 is: 9

Well, well, congratulations on your first directive!

Give Your App Users the Best Visual Experience with Help of Expert Frontend Developers

Hire Frontend Developers

ConclusionSo, in this blog, we discussed directives in AngularJS thoroughly. And now, I'm sure you can answer the question - what is AngularJS directive? - in a blink. These predefined directives in AngularJS are valuable in DOM manipulation. Moreover, you can also create your directives—developers also use Angularjs directives to update the data as soon as the modifications are made. Thus, directives in AngularJS are a significant feature in the AngularJS library. And I guess, after reading the blog, you've understood why.However, directives in AngularJS are a bit technical, and not everyone's cup of tea to learn it effortlessly or even work with it. So, what's the drill? Any solution? Well, YES! Taking the help of our experts at Radixweb.Radixweb is an award-winning software development company that has been working with Angular since its inception. We help shape your ideas and turn them into agile, scalable, and high-performance AngularJS applications. Expert knowledge of AngularJS developers helps mobilize custom and highly affordable AngularJS development, resulting in simplistic solutions incorporating all the uniqueness of your business needs. We build apps with user-friendly UX and Agile development cycles catering to your users' needs. As a top-notch AngularJS web development company, we are always happy to create modern digital solutions with unmatched capabilities and engagement qualities supported by flawless features.Connect with us ASAP to learn more about the directives of AngularJS and our services.

Don't Forget to share this post!

Rahul Buddha

Rahul Buddha

Verified
Verified Expert in Engineering
View All Posts

About the Author

Rahul Buddha works as a Technical Innovator with 9 years of experience at Radixweb. His deep-seated knowledge of Node.js, Angular.js, AWS services, Vue.js and MongoDB drives the development of several successful and high-performing applications for our organization. His keen eye for the latest technologies and trends strives to bring innovation to the table every time.