AngularJS支持模塊化方法。模塊用于將邏輯(例如服務,控制器,應用程序等)與代碼分離,并保持代碼的整潔。我們在單獨的js文件中定義模塊,并根據module.js文件命名它們。在以下示例中,我們將創(chuàng)建兩個模塊-
Application Module(應用模塊)?用于使用初始化應用程序controller(s)。
Controller Module(控制器模塊) ?用于定義控制器。
下面是一個名為mainApp.js的文件,其中包含以下代碼-
var mainApp = angular.module("mainApp", []);在這里,我們使用 angular.module 函數聲明一個應用程序 mainApp 模塊,并向其傳遞一個空數組。這個數組通常包含相關模塊。
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});在這里,我們使用mainApp.controller函數聲明一個控制器studentController模塊。
<div ng-app = "mainApp" ng-controller = "studentController"> ... <script src = "mainApp.js"></script> <script src = "studentController.js"></script> </div>
在這里,我們使用使用ng-app指令的應用程序模塊,以及使用ngcontroller指令的控制器。 我們在HTML主頁面中導入mainApp.js和studentController.js。
以下示例顯示了上述所有模塊的用法。
<html>
<head>
<title>Angular JS Modules</title>
<script src = "https://cdn.staticfile.org/angular.js/1.3.14/angular.min.js"></script>
<script src = "/run/angularjs/src/module/mainApp.js"></script>
<script src = "/run/angularjs/src/module/studentController.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS 模塊使用示例</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>輸入名字:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>輸入姓氏: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
</tr>
<tr>
<td>姓名: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>科目:</td>
<td>
<table>
<tr>
<th>名稱</th>
<th>分數</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>測試看看?/?var mainApp = angular.module("mainApp", []);mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Sea",
lastName: "Gull",
fees:500,
subjects:[
{name:'物理',marks:70},
{name:'化學',marks:80},
{name:'數學',marks:65},
{name:'英語',marks:75},
{name:'語文',marks:67}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});輸出結果

在網絡瀏覽器中打開文件textAngularJS.htm。