please observe the code snippets I've provided below.
<div ng-app = "">
<input type="text" autofocus="autofocus" placeholder="Enter your name"
ng-model="name"><br>
Hai {{name}}!
</div>
<div ng-app = "mainApp">
<input type="text" autofocus="autofocus" placeholder="Enter your name"
ng-model="name"><br>
Hai {{name}}!
</div>
I'm getting the desired output in case 1 where as in case 2 I'm getting output as Hai {{name}}!
please tell me the difference between the two cases and how does naming a ng-app module is affecting the output.
First of all, try to understand the concept of ng-app.
Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the or tags.
- ng-app means: That page has Angular in it!
- ng-app="module" means: That page has Angular in it and necessary controls/services/etc are defined in that module.
- ng-app defines the main or bootstrap module of your application, which should perform the initialization task of your application.
Like in java you have many methods and classes but you define one main method as starting point. Similarly, in angular you have many module, however, you define one module as the starting point of application.
Case 1 : This will define the controller function in the global scope.
Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the .controller method of your Angular Module for your application
HTML
<div ng-app="" ng-controller="GreetingController">
<input type="text" autofocus="autofocus" placeholder="Enter your name"
ng-model="name"><br>
Hai {{name}}!
</div>
Angular
function GreetingController($scope) {
$scope.name = "Hello";
}
Case 2 : This will define the module scope
You can specify an AngularJS module to be used as the root module for the application. This module will be loaded into the $injector when the application is bootstrapped.
HTML
<div ng-app="myApp" ng-controller="GreetingController">
<input type="text" autofocus="autofocus" placeholder="Enter your name"
ng-model="name"><br>
Hai {{name}}!
</div>
Angular
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.name = 'Hola!';
}]);
Official documentation ng-app