Site icon ParallelCodes

AngularJS – Using ng-app Directive

AngularJS Ng-App Directive

We can call Ng-App directive as a starting point of your AngularJS application. ng-app tells AngularJS to start-off from this point with scripting the app. This directive can be used with HTML’s <html>,<body>,<div> tags, and also with other HTML tags.

Example:
<html>
<head>
<title>AngularJS - Example</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
</head>
<body ng-app>

<p>Where are you from: <input type="text" ng-model="countryName"/></p>
<p>You are from <b>{{countryName}}</b></p>

<p>Select any number:<select ng-model="anyNumber">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select>
</p>
<p>You selected <b>{{anyNumber}}</b></p>
</select>
</body>
</html>

Here, we are declaring ng-app directive inside HTML body tag. So the app will start from here and it is the root element. If you declare ng-app more than once, the first occurrence will be considered as the root element.

Ng-App Module name:

ng-app directive can also have a moduleName property. It is an optional property. Defining moduleName to the ng-app directive can be very useful when you are using separate angularjs scripts.

Example:

<html>
<head>
<title>AngularJS - Example</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
<style>
body
{
font-family: Arial;
padding:5px;
font-size:16px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="myController">
Date is {{date | date:'dd-MMM-yyyy'}}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
$scope.date = new Date();
});
</script>

</body>
</html>

VIEW DEMO

OUTPUT:

NOTE: module name for ng-app is case sensitive. You must declare same name in your script as well as DOM element, or else it won’t work.


Exit mobile version