Directives in angular are custom HTML attributes that tell it to change the style or behavior of the Document Object Model (DOM) elements. When we say that components are the building blocks of Angular applications, we are saying that directives are the building blocks of Angular applications.
To put it more simply, we can say that the directives in angular are instructions in the DOM. Directives specify how to place the components and the logic of Angular. Let us dive deep into what are the directives in AngularJS and learn more about its different types and their examples.
What are Directives in Angular?
We know that AngularJS extends the functionality of HTML. The use of directives in AngularJS is the main reason behind it. We use directives in AngularJS to convert a static page, an HTML page, into a dynamic page. Using a directive, we can do this without manually editing the code. For Document Object Model (DOM), directives in AngularJS are used to add specific behavior.
The Syntax of AngularJS Directives
Most of the directives in AngularJS start with ng as a prefix. ng stands for angular. But it does not always have to start with ng as a prefix. We can also use x- or data- as a prefix.
For example:
ng-init is a directive in AngularJS. It can also be written as x-ng-init or data-ng-init . All three forms have the same meaning. They are all used to perform the same task or functions.
We can also replace – by : or _ in the syntax. It will become ng:init or ng_init . All forms will have the same meaning and they will perform the same functions. You can refer to AngularJS live Project Training for more understanding of the concepts.
Example of AngularJS Directives
Let’s see the example of the directive in AngularJS with different types of syntax.
Angular directive example:
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app>
Name: <input type="text" ng-model="firstName" /> <br />
data-ng-bind: <span data-ng-bind="firstName"></span><br />
data-ng:bind: <span data-ng:bind="firstName"></span><br />
data:ng:bind: <span data:ng:bind="firstName"></span><br />
x:ng:bind: <span x:ng:bind="firstName"></span><br />
ng:bind: <span ng:bind="firstName"></span><br />
x-ng-bind: <span x-ng-bind="firstName"></span><br />
x_ng_bind: <span x_ng_bind="firstName"></span><br />
ng_bind: <span ng_bind="firstName"></span>
</body>
</html>
Output:
Name:
data-ng-bind:
data-ng:bind:
data:ng:bind:
x:ng:bind:
ng:bind:
x-ng-bind:
x_ng_bind:
ng_bind:
Now, when we write the input name in the given textbox, it will bind to all directives in the lines below and will be printed. Then the final output will look like this:
Name: John
data-ng-bind: John
data-ng:bind: John
data:ng:bind: John
x:ng:bind: John
ng:bind: John
x-ng-bind: John
x_ng_bind: John
ng_bind: John
We can see the same name appears in every output. Whenever we change the name, it will get changed in every output directive.
Types of Directives
There are two main types of directives in AngularJS.
- Built-In directives - These directives in AngularJS are already predefined. We can directly use them for different functionalities in our application.
- Custom directives – Custom directives are made by the user. They are not predefined. We can define them based on their functionality.
Let’s learn more about built-in directives and custom directives.
Built-In Directives
Built-in directives are used to manage the elements like forms, lists, and styles of the application. To put it more simply, we can say that built-in directives are used to manage the elements that the user can see on the screen.
Based on the functions of directives, built-in directives can further be classified in three diverse types.
- Components: Component directives in angular with the template.
- Structural directives: These directives change the DOM layout by adding and removing DOM elements.
- Attribute directives: These directives change the appearance or behavior of an element, component, or another directive.
Here are some examples of built-in directives in angularjs
- ng-init
- ng-bind
- ng-model
- ng-repeat
- ng-if
- ng-disable
- ng-readonly
- ng-class
- ng-style
- ng-for
- ng-switch
Custom Directives
Custom directives are user-defined directives in AngularJS. These allow the user to use desired functions to extend the functionality of HTML. Also, new directives can be created to manipulate the HTML behavior. Thus, users can create directives in angular.
Users can use the directive function to define those custom directives, and it can replace the element for which it can be used. AngularJS has a lot of popular built-in directives; still, sometimes custom directives are required.
Let’s have an introduction to the ways to implement custom directives in AngularJS.
- Element directives: It is activated when finding a matching HTML element in the HTML template. For example: <directive-name></directive-name>
- Attribute directives: It is activated when finding a matching HTML attribute in the template. For example: <div directive-name></div>
- CSS Class directive: It is activated when finding a matching CSS class in the template. For example: <div class=”directive-name: expression;”></div>
- Comment directives: It is activated when finding a matching HTML comment. For example: <!-- Directive: directive-name expression; -->
We will see further in the article how to build these custom directives with angular custom directive examples.
AngularJS Directives List
Now, we will learn which are the different types of directives in AngularJS and how they are used.
1. ng-app directive
The ng-app directive defines the root element. It runs an AngularJS application and automatically initializes or loads the application when a web page containing an AngularJS application is loaded. It is also used to load various AngularJS modules in an AngularJS application.
Example:
<div ng-app=””>...</div>
2. ng-init directive
ng-init directive initializes the data in the application of AngularJS. It defines the initial values of the data in the application.
Example:
<div ng-app=”” ng-init=”people=[{name:’Sam’,hobby:’painting’},{name:’John’,hobby:’reading’}]”>…</div>
3. ng-model directive
Ng-model directive is used to define the variable to be used in the application.
Example:
<div ng-app = "">
<p>Enter your name: <input type = "text" ng-model = "name"></p>
</div>
4. ng-repeat directive
This directive repeats the HTML element for each item in the collection. In the given an example we have iterated for the array of people.
Example:
<div ng-app=”">
<p>List of people</p>
<ol>
<li ng-repeat = ”person in people”>
{{ ‘Name:’ + people.name + ‘Hobby:’ + people.hobby }}
</li>
</ol>
</div>
These are some of the most common directives in AngularJS. Below is the list of other directives and their description.
Directive | Description |
---|
ng-app | It defines the root element of an application. |
ng-repeat | It defines a template for each data in a collection. |
ng-mouseup | It specifies the behavior on mouseup events. |
ng-non-bindable | It specifies that no data binding can happen in this element, or it’s children. |
ng-mouseover | It specifies behavior on mouseover events. |
ng-mouseover | It specifies behavior on mouseover events. |
ng-mouseleave | It specifies the behavior on mouseleave events. |
ng-mouseenter | It specifies the behavior on mouseenter events. |
ng-mousedown | It specifies behavior on mousedown events. |
ng-model-options | It specifies how updates in the model are done. |
ng-model | It binds the value of HTML controls to application data. |
ng-form | It specifies an HTML form to inherit controls from. |
ng-disabled | It specifies if an element is disables or not. |
ng-value | It specifies the value of an input element. |
ng-transclude | It specifies a point to insert transcluded element. |
ng-switch | It specifies a condition that will be used to show/hide child elements. |
ng-submit | It specifies expressions to run on onsubmit events. |
ng-style | It specifies the style attribute for an element. |
ng-srcset | It specifies the srcset attribute for the <img> element. |
ng-src | It specifies the src attribute for the <img> element. |
ng-show | It shows or hides html elements. |
ng-selected | It specifies the selected attribute of an element. |
ng-required | It specifies the required attribute of an element. |
ng-readonly | It specifies the readonly attribute of an element. |
ng-pluralize | It specifies a message to display according to en-us localization rules. |
ng-paste | It specifies the behavior on paste events. |
ng-options | It specifies <options> in a <select> list. |
ng-open | It specifies the open attribute of an element. |
ng-list | It converts text into a list (array). |
ng-keyup | It specifies the behavior of keyup events. |
ng-keypress | It specifies the behavior on keypress events. |
ng-keydown | It specifies a behavior on keydown events. |
ng-jq | It specifies that the application must use a library, like jQuery. |
ng-init | It defines initial values for an application. |
ng-include | It includes html in an application. |
ng-if | It removes the html element if a condition is false. |
ng-href | It specifies a URL for the <a> element. |
ng-hide | It hides or shows html elements. |
ng-focus | It specifies a behavior on focus events. |
ng-dblclick | It specifies a behavior on double-click events. |
ng-cut | It specifies the behavior of cut events. |
ng-csp | It changes the content security policy. |
ng-controller | It defines the controller object for an application. |
ng-copy | It specifies the behavior of copy events. |
ng-cloak | It prevents flickering when your application is being loaded. |
ng-click | It specifies an expression to evaluate when an element is being clicked. |
ng-class | It specifies CSS classes on html elements. |
ng-class-even | It is same as ng-class, but will only take effect on even rows. |
ng-class-odd | It is same as ng-class, but will only take effect on odd rows. |
ng-checked | It specifies if an element is checked or not. |
ng-blur | It specifies behavior on blur events. |
ng-change | It specifies an expression to evaluate when content is being changed by the user. |
ng-bind | It binds the content of an html element to application data. |
ng-bind-template | It specifies that the text content should be replaced with a template. |
ng-bind-html | It binds the inner HTML of an HTML element to application data, and also removes dangerous code from the html string. |
These directives are built-in, so they are easy to implement. You can check Web Design and Web Development Course Online for more practice and examples on this topic.
Scopes in Directives
The scope has a particularly significant role in AngularJS. It acts as an intermediary between the Controller and the View (HTML) in AngularJS. Every angular directive scope object created by a controller or any other directive or service is inherited from the parent scope.
All directives have their angular directive scope. The scope uses directives to access data and methods inside a template and reference function. A directive never creates its own scope. It must be defined explicitly. By default, directives use their parent scope (from where it is called).
We can change the default angular directive scope using the scope property just like constraints, templates, etc. The value of the scope attribute defines how the scope of the directive will behave. The values are true and false. We can define the scope property in 3 ways. Here are different cases of using the scope in a directive:
- There is no value assigned to the scope or it is set as false
- The scope value is set as true
- Isolated scope
Let’s get to know more about the child scope and isolated scope.
1. Child Scope in Directives with Example
When we declare scope: true at that time the DDO directive defines its own scope. This new scope is inherited from the scope of its parent controller. In this case, scope binding flow is only one way from the parent to the directive scope so any directive change is not reflected in the parent scope, but when we change the parent scope it is reflected in the directive scope
Angular directive example:
<div ng-app="test">
<div ng-controller="parentController">
<h2>Hey {{name}}</h2>
<div>
Change Form Header : <input type-="text" ng-model="name" />
</div>
<br/>
<hr/>
<div directive-with-true-scope></div>
</div>
</div>
<script>
var app = angular.module("test", []);
app.controller("parentController", function($scope) {
$scope.name = "Hitesh";
});
app.directive("directiveWithTrueScope", function() {
return {
restrict: "A",
scope: true,
template: "<div>Your name is : {{name}}</div>" +
"Change your name : <input type='text' ng-model='name' />"
};
});</script>
In the above example, if we change the name in the header textbox, it is reflected in the directive scope, but when we change the directive scope it is not reflected in the parent scope if you want to reflect the parent scope, you have to use $parent for that.
2. Isolated Scope in Directives with Example
When we declare a scope: {} as an object in a DDO, then the directive creates a new isolated scope. And the scope does not inherit from the parent scope. So, if we want to access the values of the parent scope, we must declare it as a scope property in DDO, and this gets the property through directive attributes.
In isolated scope we can define scope property by using three prefixes.
- @ : One way binding
- = : Two-way binding
- & : Method binding
Example of isolated scope:
<div ng-app="app">
<div class="parent" ng-controller="MainCtrl">
<div class="line">
Name inside parent scope is:<input type="text" ng-model="name" />
</div>
<div class="line">
Last name inside parent scope is:
<input type="text" ng-model="lastName" />
</div>
<br/>
<hr/>
<div class="directive" my-directive
name="{{name}}"
last-name="lastName"
></div>
</div>
</div>
<script>
var app = angular.module("app", []);
app.controller("MainCtrl", function( $scope ){
$scope.name = "Hitesh";
$scope.lastName = "Jariwala";
});
app.directive("myDirective", function(){
return {
restrict: "EA",
scope: {
name: "@",
lastName: "="
},
template: [
"<div class='line'>",
"Name using @ : <input type='text' ng-model='name' /><br/>",
"</div><div class='line'>",
"Last name using =: <input type='text' ng-model='lastName' /><br/></div>"].join("")
};
});</script>
In the above example, if we change the first name in the parent scope so that it is reflected in the directive scope, but if we change the first name in the directive scope, then it will not be reflected in the parent scope due to one-way binding, just like if we change the last name in the parent scope, which is reflected in the scope of the directive and also if we change the last name in the scope of the directive, it will be reflected in the parent scope due to two-way binding just like we can pass parent scope method in directive scope and call from the directive.
How to Create New AngularJS Directives [Step-by-Step]
These are the custom directives that are made by the user. Previously we have learned some basics about custom directives. Here, we will get to know how to create directive angular.
How to Add Directives
New directives are created by using the .directive function. To invoke a new directive, we have to make an HTML element that has the same tag name as the new directive.
While naming a directive, we must use a camel case name like myNewDirective , but while invoking it, we must use the name separated with – like my-new-directive.
Angular 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>
We can invoke a directive by using different methods. That are
- Element name
- Attribute
- Class
- Comment
Using all the methods of above, it will produce the same output.
We can add some restrictions to the directive. We can restrict the directive to be invoked by some of the methods only.
For example, by adding a restrict property with the value “C”, the directive can only be invoked by the class.
<script>
var app = angular.module(“myApp”,[]);
App.directive(“myNewDirective”, function(){
return{
restrict : “C”
template : “<h1>Made by a directive! </h1>”
};
});
</script>
There are some legal restrict values.
- E – for Element name
- A – for Attribute
- C – for Class
- M – for Comment
The default restrict value is EA. This means that both Element names and attribute names can invoke the directive.
Getting Started with AngularJS Directive
AngularJS directives are custom elements in HTML, such as an attribute, element name, comment, or CSS class. They tell AngularJS to attach a specified behavior to that DOM element, or even transform the DOM element and its children. Simply, when we create a directive, AngularJS will treat this element differently.
Step 1: Building a reusable component
Directives in AngularJS can also be used to create a reusable component. Here is an example of a user box component.
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 or Setup
Directives are built-in in the AngularJS library. The angular directive template is easy to use. Here angular directive template is given. A sample directive can be created as below:
angular.module('simpleDirective', [])
.directive('helloData', function() {
return {
template: 'My name is {{data}}'
};
});
It can be used in the controller given below:
angular.module('app', ['simpleDirective'])
.controller('Controller', ['$scope', function($scope) {
$scope.data = 'John';
}]);
HTML code:
<div ng-controller="Controller">
<div hello-data></div>
</div>
Output:
My name is John
Step 3: Success/Error pop-up message using a simple link function
The angular directive link function is used to manipulate DOM in custom directives. It takes three attributes as input in the sequence. These attributes are scope, element, and attribute. This angular directive link function is used to create success or error pop-up messages in the application.
Example of the link function creating 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: Your First Directive
Now we will build a simple directive. A directive that will give a square of number 2.
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 2 is: {{2*2}} </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 2 is: 4
Event Handling in Directives
AngularJS directives consists of some directives which can be used to execute custom behaviors in DOM events. These behaviors include mouse click, double click, enter, key press, etc.
We can add AngularJS event listeners to our HTML elements by using the directives from below.
- ng-blur
- ng-change
- ng-click
- ng-copy
- ng-cut
- ng-dblclick
- ng-focus
- ng-keydown
- ng-keypress
- ng-keyup
- ng-mousedown
- ng-mouseenter
- ng-mouseleave
- ng-mousemove
- ng-mouseup
- ng-mouseover
- ng-paste
These are the event directives. Using these directives, we can run AngularJS functions which includes user events.
Note: An AngularJS event should not overwrite an HTML event, both events will be executed.
Looking to master Python? Discover the best course in Python that offers a unique learning experience. Unlock your coding potential today!
Conclusion
In this article, we learned about directives in AngularJS. The predefined directives in AngularJS are helpful in DOM manipulation. We can also create our own directives. Angularjs directives are used in updating data as soon as the changes are made. Thus, directives are a very important feature in the AngularJS library. For more clarification of concepts, you can go to the official documentation of AngularJS or you can visit the KnowledgeHut’s Angular Live Project Training.