Understanding Directives in AngularJS
Q: What is a directive in AngularJS and how do you create one?
- AngularJS
- Junior level question
Explore all the latest AngularJS interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create AngularJS interview for FREE!
In AngularJS, a directive is a reusable component that
encapsulates a piece of HTML and its associated behavior. Directives allow you
to extend the functionality of HTML and create custom elements, attributes, and
classes that can be used throughout your application.
There are several types of directives in AngularJS,
including:
- Element
directives: create custom HTML elements
- Attribute
directives: modify the behavior of existing HTML elements
- Class
directives: apply behavior to elements with a specific class
To create a directive in AngularJS, you can use the directive
method of the angular.module object. Here's an example:
angular.module('myApp').directive('myDirective', function() { return { restrict: 'E', template: '<div>Hello, {{name}}!</div>', scope: { name: '@' } }; });
In this example, we define a new directive called myDirective
using the directive method. The restrict property tells AngularJS
how the directive can be used (E for element, A for attribute,
and C for class), and the template property defines the HTML
content of the directive.
We also define a scope object, which specifies the
inputs and outputs of the directive. In this case, we define a single input
called name, which is passed to the directive as an attribute and
displayed in the template using double curly braces.
Once defined, the directive can be used in your HTML code
like any other HTML element:
<my-directive name="John"></my-directive>
In this example, we use the myDirective element to
display a custom message that greets the user by name.
By creating custom directives in AngularJS, you can
encapsulate complex functionality, improve code organization and reusability,
and create a more modular and maintainable application.


