AngularJS- What are the directives in AngularJS?

In previous examples, my first html web page using AngularJS and example to add the two text fields, you have noticed that we were using some keywords like ng-App and ng-Model in the examples to enable the AngularJS features. These are called by built in AngularJS directives.

In this article we will discuss these AngularJS directives. First let’s start with the ng-App directive.

ngApp directive

ngApp declares the root element of the your Angular application. If you miss this attribute then html page behaves as usual. If you use the ng-app attribute to html tag then AngularJS will work for the entire document. If you want to enable Angular only for the specific element then you can define ng-app attribute that element.

<html ng-app>

Note: If you want to use the AngularJS with IE7, add id=”ngapp” like as:

<html ng-app id="ng-app">

ngModel directive

The ng-model directive binds HTML elements to application data. See the below example:

<!DOCTYPE html>
<html>
<body>
  <div ng-app="">
      <b>Calculate the Amount</b>
      <div>
        Quantity:
        <input type="number" ng-model="qty">
      </div>
      <div>
        Rate:
        <input type="number" ng-model="rate">
      </div>
      <div>
        <b>Total Amount:</b> {{qty * rate}}
      </div>
    </div>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

You can see from the above that first input element is bind with the variable qty and second input element with the variable rate

ngInit directive

In the above example you can notice that both input elements have no value by default. You can set the initial values to the variables qty and rate by using the ng-init directive.

use of ng-init in angularjs

See the below example.

<div ng-app="" ng-init="qty=3;rate=5">
      <b>Calculate the Amount</b>
      <div>
        Quantity:
        <input type="number" ng-model="qty">
      </div>
      <div>
        Rate:
        <input type="number" ng-model="rate">
      </div>
      <div>
        <b>Total Amount:</b> {{qty * rate}}
      </div>
    </div>
  </div>

ngRepeat directive

The ngRepeat directive instantiates a html template once per item from a collection or array. In the below example ng-repeat creates the li element for each digit in the nums array. See the following:

 <div ng-app="" ng-init="nums=[1,2,3,4,5,6,7,8,9,10];">
      <ul>
        <li ng-repeat="x in nums">
          {{x}}. 
        </li>
      </ul>
  </div>

Output will be:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

Right now I discuss only the above directives. How ever AngularJS provide many other directives, we will discuss in the upcoming articles. You can also see the full list of Angular directives.