Here we will learn what are the directives in angularjs, how to use directives in angularjs, different types of directives in angularjs with example.
AngularJs directives are an extension over the HTML elements and that allow you to extend the HTML elements behavior by adding special attribute prefix ng-
.
AngularJS is having set of built-in directives that allow us to implement required functionality by using HTML elements in application.
The following are the few built-in directives available in angularjs.
Directive | Description |
---|---|
ng-app | This directive is used to define starting of an application. |
ng-init | This directive is used to initialize a values to variables used in application. |
ng-model | This directive is used to bind the values of input controls to application data. |
ng-repeat | This directive is used to loop through the elements in a collection and it will act like for loop. |
In angularjs, ng-app
directive is used to define starting of application and it will act as a root element for application. The ng-app
in angularjs will identify which part of HTML contains angularJs app. We will use ng-app in angularjs like as shown following
<div ng-app="">
---your code---
</div>
By using ng-init
directive in angularjs, we can assign values to the variables during an application initialization. Declaration of ng-init
in angularjs like as shown following
<div ng-app="" ng-init="val1=hi">
---your code---
</div>
The ng-model
directive in angularjs is used to get value of input controls like textbox, label, etc and use that value in angular application wherever we required. Generally, we will use the ng-model directive in angularjs like as shown following
<div ng-app="">
<input type="text" id="txtname" ng-model="name" />
<p>Your Username: {{name}}</p>
</div>
The ng-repeat
directive in angularjs is used to loop through items in collection element and it will act as for loop. We can use ng-repeat directive in angularjs application like as shown following
<div ng-app="" ng-init="employees=['Suresh','Rohini','Saineshwar']">
<ul>
<li ng-repeat="name in employees">
{{ name }}
</li>
</ul>
</div>
We will see all these angularjs directives with simple example.
Following is the example of using directives in angularjs applications.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs Directives Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="">
<div>
<input type="text" id="txtname" ng-model="name" />
<p>Your Nmae: {{name}}</p>
</div>
<div ng-init="employees=['Suresh','Rohini','Saineshwar']">
<p>Employee Details:</p>
<ul>
<li ng-repeat="name in employees">
{{ name }}
</li>
</ul>
</div>
</body>
</html>
Now run application and check output that would be like as shown below.
Following is the result of using directives in angularjs applications.