AngularJS实现使用路由切换视图的方法

下面是一个简单的学生信息管理实例。

注意:除了引用angular.js之外,还要引用angular-route.js。

1、创建index.html主视图

在index.html主视图中,我们将会把多个视图共有的东西都放在里面,例如菜单。在这个例子中,我们仅仅把应用的标题放在里面,然后再用ng-view指令来告诉Angular把视图显示在哪儿。

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" ng-app="StuApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>学生信息</title> <script src="https://www.jb51.net/Scripts/angular.min.js"></script> <script src="https://www.jb51.net/Scripts/angular-route.min.js"></script> <script src="https://www.jb51.net/controllers.js"></script> </head> <body> <h1>学生信息</h1> <div ng-view></div> </body> </html>

2、创建list.html列表视图

<table> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> <tr ng-repeat="student in StudentList"> <td>{{student.id}}</td> <td><a ng-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> <a href="#/">返回</a> </div>

4、创建controllers.js控制器脚本

//创建模块 var StuServices = angular.module("StuApp", ['ngRoute']); //在URL、模板和控制器之前建立映射关系 function StuRouteConfig($routeProvider) { $routeProvider.when('https://www.jb51.net/', { controller: 'ListController', templateUrl: 'list.html' }).when('/view/:id', { controller: 'DetailController', templateUrl: 'detail.html' }).otherwise({ redirectTo: 'https://www.jb51.net/' }); } //配置路由,以便学生服务能够找到它 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]; })

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgpds.html