How to Use Directives in Angularjs?

The use of Directives in Angularjs greatly expands the working capacity of HTML. You can use many directives in AngularJs. You can use them in your project according to your need. Friends, if you want, you can also make your own Directive according to your need.

Directives are a new attribute in AngularJS that are used to extend HTML. Angularjs has a set of built-in instructions that provide the functionality of your applications. Apart from this, it also lets you define your own instructions.

AngularJS is an attractive frame for web developers, it is actually a completely different way of building applications.

ng-app Directive

It starts an AngularJS application by defining the Directive Root Element and it automatically starts or bootstrap AngularJS applications when the web page which contains the applications is loaded. Apart from this, various AngularJS modules can also be loaded using this instruction.

<div ng-app="" ng-init="firstName='Jyoti'">
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }} </p>
</div>

ng-init Directive

These instructions are very important at the start of AngularJS Applications Data. It is used to assign the values ​​of different variables to be used.

<div ng-app = "" ng-init = "countries = [{locale:'en-IN',name:'India'}, 
{locale:'en-PAK',name:'Pakistan'}, {locale:'en-AF',name:'Afghanistan'}]">
...
</div>

ng-model Directive

It connects the values ​​of AngularJS Application Data to HTML Input Controls.

<div ng-app = "">
...
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>

ng-repeat Directive

ng-repeat Repeats HTML elements for each item in a Directive Collection.

<div ng-app = "">
...
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>

For Example

<!DOCTYPE html>
<html>
<head>
<title>AngularJS Directives Example</title>
<script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries =
[{locale:'en-IN',name:'India'},
{locale:'en-GB',name:'United Kingdom'},
{locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
</body>
</html>
AngularJS Directives Example

Sample Application

Enter your Name:

Hello !

List of Countries with locale:

  1. {{ ‘Country: ‘ + country.name + ‘, Locale: ‘ + country.locale }}