您的位置:首页 > Web前端 > AngularJS

举例讲解AngularJS中的模块

2015-06-17 00:00 1666 查看

AngularJS支持模块化的方法。模块用于单独的逻辑表示服务,控制器,应用程序等,并保持代码的整洁。我们在单独的js文件中定义的模块,并将其命名为按照module.js文件形式。在这个例子中,我们要创建两个模块。

Application Module - 用于初始化控制器应用程序

Controller Module - 用于定义控制器

应用模块

mainApp.js

var mainApp = angular.module("mainApp", []);


在这里,我们已经声明使用 angular.module 功能的应用程序 mainApp 模块。我们已经通过了一个空数组给它。此数组通常包含从属模块。

控制器模块

studentController.js

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;
   }
  };
});


在这里,我们已经声明采用studentController模块的mainApp.controller功能的控制器。

使用模块

<div ng-app="mainApp" ng-controller="studentController">
..
<script src="mainApp.js"></script>
<script src="studentController.js"></script>


在这里,我们使用 ng-app 指令和控制器采用ng-controller指令应用模块。我们已经在主要的HTML页面导入mainApp.js和studentController.js。

示例

下面的例子将展示上述所有模块。

testAngularJS.htm

<html>
  <head>
 <title>Angular JS Modules</title>
 <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 Sample Application</h2>
 <div ng-app="mainApp" ng-controller="studentController">
 <table border="0">
 <tr><td>Enter first name:</td><td><input type="text" ng-model="student.firstName"></td></tr>
 <tr><td>Enter last name: </td><td><input type="text" ng-model="student.lastName"></td></tr>
 <tr><td>Name: </td><td>{{student.fullName()}}</td></tr>
 <tr><td>Subject:</td><td>
 <table>
  <tr>
    <th>Name</th>
    <th>Marks</th>
  </tr>
  <tr ng-repeat="subject in student.subjects">
    <td>{{ subject.name }}</td>
    <td>{{ subject.marks }}</td>
  </tr>
 </table>
 </td></tr>
 </table>
 </div>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
 <script src="mainApp.js"></script>
 <script src="studentController.js"></script>
</body>
</html>


mainApp.js


var mainApp = angular.module("mainApp", []);

studentController.js
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; } }; });


输出

在Web浏览器打开textAngularJS.htm。看到结果如下。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AngularJS