AngularJS directives are used to extend HTML. These are special properties starting with the ng- prefix. We will discuss the following directives:
ng-app directive
Theng-app directive starts an AngularJS application. It defines the root element. It automatically initializes or starts the application that loads the web page containing the AngularJS application. It is also used to load various AngularJS modules into AngularJS applications. In the example below, we define the default AngularJS application using the ng-app attribute of the div element.
<div ng-app=""> ... </div>
ng-init command
The ng-init directive initializes the data of an AngularJS application. It is used to put values into variables used in applications. In the following example, we will initialize the countries array. Use JSON syntax to define the countries array.
<div ng-app="" ng-init="countries=[{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]"> ... </div>
ng-model directive
ng-model directive defines models/variables used in AngularJS applications. In the example below, we define a model named "name".
<div ng-app=""> ... <p>Enter your Name: <input type="text" ng-model="name"></p> </div>
ng-repeat directive
Theng-repeat directive repeats each item in a collection of html elements. In the example below, we have iterated over the array countries.
<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>
Example
The following example will demonstrate all the above commands.
testAngularJS.html
<html> <title>AngularJS Directives</title> <body> <h1>Sample Application</h1> <div ng-app="" ng-init="countries=[{locale:'en-US',name:'United States'}, {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> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
Output
Open textAngularJS.html in your web browser. Enter a name and see the results below.