AngularJS实现使用路由切换视图的方法
本文实例讲述了AngularJS实现使用路由切换视图的方法。分享给大家供大家参考,具体如下:
下面是一个简单的学生信息管理实例。
注意:除了引用angular.js之外,还要引用angular-route.js。
1、创建index.html主视图
在index.html主视图中,我们将会把多个视图共有的东西都放在里面,例如菜单。在这个例子中,我们仅仅把应用的标题放在里面,然后再用ng-view指令来告诉Angular把视图显示在哪儿。
<!DOCTYPEhtml> <htmlxmlns="http://www.w3.org/1999/xhtml"ng-app="StuApp"> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <title>学生信息</title> <scriptsrc="/Scripts/angular.min.js"></script> <scriptsrc="/Scripts/angular-route.min.js"></script> <scriptsrc="controllers.js"></script> </head> <body> <h1>学生信息</h1> <divng-view></div> </body> </html>
2、创建list.html列表视图
<table>
<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
<trng-repeat="studentinStudentList">
<td>{{student.id}}</td>
<td><ang-href="#/view/{{student.id}}">{{student.name}}</a></td>
<td>{{student.sex}}</td>
<td>{{student.age}}</td>
</tr>
</table>
3、创建detail.html详细视图
<div>
<div><strong>学号:</strong>{{Student.id}}</div>
<div><strong>姓名:</strong>{{Student.name}}</div>
<div><strong>性别:</strong>{{Student.sex}}</div>
<div><strong>年龄:</strong>{{Student.age}}</div>
<ahref="#/">返回</a>
</div>
4、创建controllers.js控制器脚本
//创建模块
varStuServices=angular.module("StuApp",['ngRoute']);
//在URL、模板和控制器之前建立映射关系
functionStuRouteConfig($routeProvider){
$routeProvider.when('/',{
controller:'ListController',
templateUrl:'list.html'
}).when('/view/:id',{
controller:'DetailController',
templateUrl:'detail.html'
}).otherwise({redirectTo:'/'});
}
//配置路由,以便学生服务能够找到它
StuServices.config(StuRouteConfig);
//一些虚拟的学生信息
StudentList=[{id:0,name:'张三',sex:'男',age:18},
{id:1,name:'李四',sex:'女',age:15},
{id:2,name:'王五',sex:'男',age:16}
];
//列表模板
StuServices.controller("ListController",function($scope){
$scope.StudentList=StudentList;
})
//详细模块:从路由信息(从URL中解析出来的)中获取邮件id,然后用它找到正确的邮件对象
StuServices.controller("DetailController",function($scope,$routeParams){
$scope.Student=StudentList[$routeParams.id];
})
更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS入门与进阶教程》及《AngularJSMVC架构总结》
希望本文所述对大家AngularJS程序设计有所帮助。