AngularJS – ng-app 指令
angularjsweb developmentfront end technology更新于 2026/1/7 0:22:17
AngularJS 中的 ng-app 指令 用于自动引导 AngularJS 应用。该指令指定应用的根元素,通常放置在页面根元素附近,例如 <html> 或 <body> 标签。该指令声明了应用启动的根上下文。
使用 ngApp 指令 的注意事项 −
- 每个 HTML 元素只能引导一个应用。如果您声明多个 ngApp 组件,则第一个出现的 ngApp 元素将被视为自动引导的根元素。要在 HTML 中运行多个应用程序,应使用 angular.bootstrap 方法。
- 请勿将 AngularJS 应用程序嵌套在一起。
- Transclusions 指令不应与 ngApp 指令在同一元素上使用。一些包含指令包括 ngIf、ngInclude、ngView 等。
语法
<element ng-app="">..Content..</element>
− ngApp 指令示例
创建文件"ngApp.html"在您的 Angular 项目目录中并复制粘贴以下代码片段。
<!DOCTYPE html>
<html>
<head>
<title>ngApp Directive</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
Welcome to Tutorials Point
</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 文件运行即可。您将在浏览器窗口中看到以下输出。
.png)
示例 2
在您的 Angular 项目目录中创建文件"ngApp.html",并复制粘贴以下代码片段。
<!DOCTYPE html>
<html>
<head>
<title>ngApp Directive</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-App="" style="text-align: center;">
<h1 style="color: green;">
Welcome to Tutorials Point
</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 文件运行即可。您将在浏览器窗口中看到以下输出。
.png)

