AngularJS支持模塊化方法。模塊用于將邏輯(例如服務(wù),控制器,應(yīng)用程序等)與代碼分離,并保持代碼的整潔。我們在單獨(dú)的js文件中定義模塊,并根據(jù)module.js文件命名它們。在以下示例中,我們將創(chuàng)建兩個(gè)模塊-
Application Module(應(yīng)用模塊)
?用于使用初始化應(yīng)用程序controller(s)
。
Controller Module
(控制器模塊) ?用于定義控制器。
下面是一個(gè)名為mainApp.js的文件,其中包含以下代碼-
var mainApp = angular.module("mainApp", []);
在這里,我們使用 angular.module 函數(shù)聲明一個(gè)應(yīng)用程序 mainApp 模塊,并向其傳遞一個(gè)空數(shù)組。這個(gè)數(shù)組通常包含相關(guān)模塊。
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函數(shù)聲明一個(gè)控制器studentController模塊。
<div ng-app = "mainApp" ng-controller = "studentController"> ... <script src = "mainApp.js"></script> <script src = "studentController.js"></script> </div>
在這里,我們使用使用ng-app指令的應(yīng)用程序模塊,以及使用ngcontroller指令的控制器。 我們在HTML主頁面中導(dǎo)入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>分?jǐn)?shù)</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:'化學(xué)',marks:80}, {name:'數(shù)學(xué)',marks:65}, {name:'英語',marks:75}, {name:'語文',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; });
輸出結(jié)果
在網(wǎng)絡(luò)瀏覽器中打開文件textAngularJS.htm。