AngularJS 路由允许我们通过不同的 URL 访问不同的内容。
通过 AngularJS 可以实现多视图的单页Web应用(single page web application,SPA)。 通常我们的URL形式为 http://runoob.com/first/page,但在单页Web应用中 AngularJS 通过 #! 标记 实现,例如:
127.0.0.1:8080/#!/index
127.0.0.1:8080/#!/list
127.0.0.1:8080/#!/article
-
我们模拟一个简单的网站应用
- 首页
- 列表页
- 商品详情页
-
单页面应用的传递参数的方式
- 在详情页面的路由中 配置参数占位符
- 在列表页的文章链接中 配置真正的参数
- 在详情页面的控制器中获取到路由参数
文件准备
- 新建tpl文件夹下有三件html页面:
-
index.html
我是首页{{ msg }}
-
article.html
我是详情页
-
list.html
<ul> <li><a href="#!/article/1/我是第1篇文章">我是第1篇文章</a></li> <li><a href="#!/article/2/我是第2篇文章">我是第2篇文章</a></li> <li><a href="#!/article/3/我是第3篇文章">我是第3篇文章</a></li> <li><a href="#!/article/4/我是第4篇文章">我是第4篇文章</a></li> </ul>
-
当前html下
<body ng-app="myApp">
<a href="#!/index">首页</a>
<a href="#!/list">列表页</a>
<div ng-view></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-route/angular-route.js"></script>
<script>
var app = angular.module('myApp',['ngRoute']);
// angularjs是根据形参的名字去传递参数的
app.config(function($routeProvider){
// 路由的具体配置需要写在这个函数当中
// 当...时候
$routeProvider
.when("/index",{
templateUrl:'./tpl/index.html',
controller:'indexCtrl'
})
.when("/list",{
templateUrl:'./tpl/list.html',
controller:'listCtrl'
})
//参数占位符
.when("/article/:id/:title",{
templateUrl:'./tpl/article.html',
controller:'articleCtrl'
})
// .otherwise('/index')
otherwise({
//或者重定向也可以
redirectTo: '/home'
});
})
app.controller('indexCtrl',function($scope){
$scope.msg = "我是首页中的数据";
})
app.controller('listCtrl',function($scope){
$scope.msg = "我是列表页中的数据";
})
app.controller('articleCtrl',function($scope,$routeParams){
console.log($routeParams.id);
console.log($routeParams.title);
});
</script>
</body>
总结:以上只是angular路由最基本的思想的小demo,体会angular单页面的实现方式