AngularJS – ng-app 指令

AngularJS 中的ng-app 指令用于自动引导 AngularJS 应用程序。该指令给出了应用程序的根元素,通常放置在页面的根元素附近,例如<html> <body>标签。该指令声明应用程序将从中启动的根上下文。

使用ngApp 指令时的注意事项-

  • 每个 HTML 元素只能引导一个应用程序。如果你声明了多个ngApp组件,第一个出现的ngApp元素将被视为自动引导的根元素。要在 HTML 中运行多个应用程序,应该使用angular.bootstrap方法。

  • 不要将 AngularJS 应用程序相互嵌套。

  • 不应在与ngApp相同的元素上使用Transclusions指令。一些包含指令是ngIf、ngInclude、ngView等。

语法

<element ng-app="">..Content..</element>

示例 - ngApp 指令

在您的 Angular 项目目录中创建一个文件“ ngApp.html ”并复制粘贴以下代码片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngApp Directive</title>

      <script xx_src="https://cdn.staticfile.org/angularjs/1.6.9/angular.min.js"></script>
   </head>

   <body style="text-align: center;">
      <h1 style="color: green;">
         Welcome to nhooo.com
      </h1>
      <h2>
         AngularJS | ngApp Directive
      </h2>

      <div ng-app="" ng-init="course='AngularJS'">
         <p>Start Learning the latest <b>{{course}}</b> features now...</p>
      </div>
   </body>
</html>
输出结果

要运行上述代码,只需转到您的文件并将其作为普通 HTML 文件运行即可。您将在浏览器窗口中看到以下输出。

示例 2

在您的 Angular 项目目录中创建一个文件“ ngApp.html ”并复制粘贴以下代码片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngApp Directive</title>

      <script xx_src="https://cdn.staticfile.org/angularjs/1.6.9/angular.min.js"></script>
   </head>

   <body ng-App="" style="text-align: center;">
      <h1 style="color: green;">
         Welcome to nhooo.com
      </h1>
      <h2>
         AngularJS | ngApp Directive
      </h2>

      <div>
         <p>Enter the Course: <input type="text" ng-model="course" /></p>
         <p>Course: <span ng-bind="course"></span></p>
      </div>
   </body>
</html>
输出结果

要运行上述代码,只需转到您的文件并将其作为普通 HTML 文件运行即可。您将在浏览器窗口中看到以下输出。