AngularJs 中 ng-app 指令的功能

Functionality of ng-app directive in AngularJs

请注意我在下面提供的代码片段。

案例 1:

AngularJS 示例应用程序

  <div ng-app = "">
     <input type="text" autofocus="autofocus" placeholder="Enter your name"         
           ng-model="name"><br>
     Hai {{name}}!
  </div>

案例二:

AngularJS 示例应用程序

  <div ng-app = "mainApp">
     <input type="text" autofocus="autofocus" placeholder="Enter your name" 
          ng-model="name"><br>
     Hai {{name}}!
  </div>

我在案例 1 中得到了所需的输出,而在案例 2 中我得到了输出 Hai {{name}}!

请告诉我这两种情况之间的区别以及命名 ng-app 模块如何影响输出。

首先尝试理解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.

就像在java中你有很多方法和类但是你定义了一个主要的 方法作为起点。同样,在 angular 你有很多模块, 但是,您将一个模块定义为应用程序的起点。

Case 1 : This will define the controller function in the global scope.

虽然Angular允许您在全局范围内创建控制器函数,但不推荐这样做。在实际的应用程序中,您应该为您的应用程序使用 Angular 模块的 .controller 方法

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

您可以指定一个 AngularJS 模块作为应用程序的根模块。该模块将在应用程序启动时加载到 $injector 中。

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!';
}]);

官方文档ng-app