本文实例讲述了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="/Scripts/angular.min.js"></script><script src="/Scripts/angular-route.min.js"></script><script src="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("/", {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入门与进阶教程》及《AngularJS MVC架构总结》
希望本文所述对大家AngularJS程序设计有所帮助。