Objectives and outcomes

In this tutorial we are going to learn about various directives used in angular-js. Before we start with various types of directives we should understand what is directive. Directives are extended html attributes with ng- prefix which provide functionality to the application. Example of various built-in directives are ng-app, ng-model, ng-init, ng-bind, ng-repeat etc.

Directives functionality

1- ng-app: It is used to declare the angular-js application. Most time we use this attribute in body tag to make the whole document behave as angular-js application while you can also declare this attribute inside an html element. HTML element which consist of ng-app is the only portion of the document which will behave as angular-js application.
2- ng-init: This directive is used to initialize application data. Well most times we do not use ng-init to initialize data instead of that we use controllers. Learn about controllers from Here.
3- ng-model: It is used to bind the value of HTML control like input and textarea to the application data. It is also used in validation(date, required, email) and to check the status of data(invalid, dirty, error).
4- ng-repeat: It is used to repeat an HTML element. It is like looping through the array.

Use of ng-init, ng-repeat and ng-model

<meta charset="utf-8">
<title>AngularJS Directives</title>
<script src="angular-1.4.6/angular.min.js"></script>
<div ng-app="" ng-init="name='developers';names=['Alfred','Joseph','Tony'];">
Name:<input type="text" ng-model="name"><br/>
<p>Welcome {{name}}</p><br/>
<li ng-repeat="person in names">{{person}}</li>



Welcome {{name}}

  • {{person}}

In the above code we have initialized the application variable 'name' to 'developers' and also we have bind it with the input control. We have also declared an array names and we loop through the array using ng-repeat. As soon as we change the value inside input box the application data gets changed. We have accessed the application data by using {{}} (curly braces).