以下是演示angular路由切换的demo.
主页:index.html
<!doctype html>
<html ng-app="bookStoreApp"><head>
<meta charset="UTF-8"> <title>BookStore</title> <script src="framework/1.3.0.14/angular.js"></script> <script src="framework/1.3.0.14/angular-route.js"></script> <script src="framework/1.3.0.14/angular-animate.js"></script> <script src="js/app.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/services.js"></script> <script src="js/directives.js"></script></head><body>
<div ng-view> </div></body></html>
模板文件(html碎片文件)tpls/:
hello.html:
<p>{
{greeting.text}},Angular</p>
bookList.html:
<ul>
<li ng-repeat="book in books"> 书名:{ {book.title}} 作者:{ {book.author}} </li></ul>
控制器文件js/:
controllers.js:
var bookStoreCtrls = angular.module('bookStoreCtrls', []);
bookStoreCtrls.controller('HelloCtrl', ['$scope',
function($scope) { $scope.greeting = { text: 'Hello' }; }]);bookStoreCtrls.controller('BookListCtrl', ['$scope',
function($scope) { $scope.books =[ {title:"《AngularJS从入门到精通》",author:"中华烟云"}, {title:"《AngularJS权威指南》",author:"中华烟云"}, {title:"《用AngularJS开发下一代WEB应用》",author:"中华烟云"} ] }]);/**
* 这里接着往下写,如果控制器的数量非常多,需要分给多个开发者,可以借助于grunt来合并代码 */
最后实现路由功能的是app.js:
var bookStoreApp = angular.module('bookStoreApp', [
'ngRoute', 'ngAnimate', 'bookStoreCtrls', 'bookStoreFilters', 'bookStoreServices', 'bookStoreDirectives' //[]内的为依赖注入的模块,ng开头的为angular自带的模块]);bookStoreApp.config(function($routeProvider) { //$routeProvider是angular-route.js提供的原生路由对象,可以通过$routeProvider.when({}).when({})....otherwise({});这种链式写法来配置路由
$routeProvider.when('/hello', { //'/hello'为路由路径,即在哈希符#后面动态输入的路径字串,如:....#/hello templateUrl: 'tpls/hello.html', //当路径为...#/hello时,调用模板文件'tpls/hello.html' controller: 'HelloCtrl' //当路径为...#/hello时,调用控制器文件'js/HelloCtrl.js }).when('/list',{ //:此时若切换到...#/list路径下 templateUrl:'tpls/bookList.html', //当路径为...#/list时,调用模板文件'tpls/bookList.html' controller:'BookListCtrl' //当路径为...#/list时,调用控制器文件'js/BookListCtrl.js }).otherwise({ //:否则默认跳转到...#/hello路径下 redirectTo: '/hello' })});注:angular-route.js提供的原生路由对象有个缺陷,就是不能深层次嵌套。要实现深层次嵌套,还得用UI-Router,源文件为angular-UI-Router.js.
UI-Router路由插件将在下一篇讲解.