1.效果图
2.文件结构
3.代码
(1)index.html
<!DOCTYPE html> <html lang="en" ng-app="usermanage"> <head> <Meta charset="UTF-8"> <title>user info demo</title> </head> <body> <h1>用户管理demo</h1> <!--使用ng-show,表明我们使用路由控制来管理页面--> <div ng-view> loading... </div><!--视图模块容器--> <script type="text/javascript" src="js/lib/angular.js"></script> <script type="text/javascript" src="js/lib/angular-route.js"></script> <script type="text/javascript" src="js/controller/IndexController.js"></script> </body> </html>
(2)list.html
<!DOCTYPE html> <html lang="en" ng-app="UserMgt"> <head> <Meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="js/lib/angular.js"></script> <script type="text/javascript" src="js/lib/angular-route.js"></script> <script type="text/javascript" src="js/controller/IndexController.js"></script> </head> <body> <table border="1"> <tr> <!--设置表头--> <td>用户名</td> <td>性别</td> <td>邮箱</td> </tr> <!--使用ng-repeat,遍历所有user--> <tr ng-repeat="user in users"> <td>{{user.username}}</td> <td>{{user.gender}}</td> <td>{{user.email}}</td> </tr> </table> </body> </html>
(3)detail.html
<!DOCTYPE html> <html lang="en" ng-app="UserMgt"> <head> <Meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="js/lib/angular.js"></script> <script type="text/javascript" src="js/lib/angular-route.js"></script> <script type="text/javascript" src="js/controller/IndexController.js"></script> </head> <body> <table border="1"> <tr> <td>用户名</td> <!--使用ng-model绑定item对象的username属性--> <td><input type="text" ng-model="item.username"></td> </tr> <tr> <td>男</td> <td><input type="text" ng-model="item.gender"></td> </tr> <tr> <td>邮箱</td> <td><input type="text" ng-model="item.email"></td> </tr> </table> </body> </html>4.controller
/*定义UserController模块*/ var usermanage=angular.module('usermanage',['ngRoute']); /*路由定义*/ usermanage.config( function ($routeProvider) { $routeProvider /*项目打开默认调到list.html页面,绑定ListController进行相应的控制*/ .when('/',{ controller:ListController,templateUrl:'./list.html' }) /*定义访问url*/ .when('/get/:id',{ /*定义绑定的控制器*/ controller:GetController,/*定义跳转的页面*/ templateUrl:'./detail.html' }) .otherwise({ /*其他情况,指定URL跳转*/ redirectTo:'/' }); } ) /*ListController 定义*/ function ListController($scope,$http){ /*获取本地的json文件*/ $http.get('./js/conf/user.json').success(function (data) { console.log(data); $scope.users=data; }); } /*GetController控制器定义*/ function GetController($scope,$http,$routeParams) { var id=$routeParams.id; /*获取本地json文件*/ $http.get('./js/conf/user.json').success(function (data){ console.log(data); $scope.item=data[id]; }) }
5.json
[ { "id": 1,"username": "situ","gender": "男","email": "gao_st@126.com" },{ "id": 2,"username": "wb","gender": "女","email": "wb@126.com" },{ "id": 3,"username": "lml","email": "lml@126.com" },{ "id": 4,"username": "wjd","email": "wjd@126.com" },{ "id": 5,"username": "lyl","email": "lyl@126.com" },{ "id": 6,"username": "wjh","email": "wjh@126.com" } ]