單頁面應用(SPA)
1、不産生頁面跳轉,提高使用者體驗。(連結使用錨點)
2、把多個功能(視圖)內建在一個頁面中。根據不同的邏輯展示不同的視圖(路由)(錨點)
3、動态生成資料,通過Ajax異步擷取。
4、和Tab欄不同(SPA可以點選前進後退)
5、外面包裝一個殼(浏覽器)模拟APP。
6、AngularJS将監聽錨點變化的事件(hashchange)進行封裝,封裝成前端路由(Route)。
不能使用錨點的點選事件,因為重複點選會重複發送請求。應該用hashchange事件。
demo.html:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>AngularJS</title>
<style>
ul li {
float:left;
background-color: pink;
text-align: center;
list-style: none;
}
ul li a {
display: block;
height: 40px;
width: 100px;
text-align: center;
text-decoration: none;
line-height: 40px;
}
.active {
background-color: yellow;
}
.clearfix:after{ /*僞元素清除浮動。父級元素引用clearfix類*/
content:"."; /*可以為空*/
display: block;
height: 0;
line-height: 0;
visibility: hidden;
clear:both; /*清除浮動*/
}
.clearfix{ /*相容ie浏覽器*/
zoom:1;
}
</style>
<script src="./angular.min.js"></script> <!-- 引入AngularJS架構(1.5.8) -->
<script src="./angular-route.min.js"></script> <!-- 引入路由子產品 -->
</head>
<body ng-app="App">
<div>
<ul class="clearfix">
<li><a href="#/index/zhangsan/12" target="_blank" rel="external nofollow" >index</a></li> <!-- 連結都是錨點。 通過"/"傳遞參數 -->
<li><a href="#/introduce" target="_blank" rel="external nofollow" >introduce</a></li>
<li><a href="#/contact" target="_blank" rel="external nofollow" >contact</a></li>
<li><a href="#/list?name=zhangsan&age=12" target="_blank" rel="external nofollow" >List</a></li> <!-- 通過"?"傳遞參數 -->
</ul>
<div class='content'>
<div ng-view></div> <!-- 占位符 -->
</div>
</div>
<script>
// 依賴ngRoute子產品
var App = angular.module('App',['ngRoute']);
// 配置路由子產品
App.config(['$routeProvider',function($routeProvider) {
// AngularJS路由中的錨點一般以"#/"開頭
$routeProvider.when('/index/:name/:id',{ //第二個"/"後的内容表示錨點中的參數(:id表示形參)
template: "<h3>Index Pages</h3>", //簡單内容可以直接使用template。 用模闆替換占位符
controller: 'IndexController' //指定視圖的控制器(視圖中的資料根據控制器動态生成。控制器可以接收錨點中的參數($routeParams))
}).when('/introduce',{
//template: "<h3>Introduce Pages</h3>"
templateUrl: './xxx.html' //複雜的内容可以用templateUrl。(發送Ajax請求,必須有伺服器才生效)
}).when('/contact',{
template: "<h3>Contact Pages</h3>"
}).when('/list',{
templateUrl: "./list.html", //視圖模闆
controller: 'ListController' //指定視圖的控制器
}).otherwise({
redirectTo: '/index' //其他情況跳轉到"/index"
});
}]);
// 錨點中的"/"傳遞參數時,必須嚴格比對對應路由;"?"傳遞參數不需要嚴格比對路由(隻比對"?"前的路由)
// 錨點中可以用"/"和"?"同時傳遞參數。 "#index/zhangsan/12?sex=男" (路由隻比對"?"前的内容)
// 控制器 $routeParams擷取錨點連結中參數的服務(通過"?"和"/"傳遞的參數都可以接收)
App.controller('IndexController',['$scope','$routeParams',function($scope,$routeParams) {
console.log($routeParams); // Object {name: "zhangsan", id: "12"}
}]);
// 控制器 $routeParams擷取錨點連結中參數的服務
App.controller('ListController',['$scope','$routeParams',function($scope,$routeParams) {
console.log($routeParams); // Object {name: "zhangsan", age: "12"}
$scope.items = ['html','css','js']; //模拟擷取的動态資料
}]);
</script>
</body>
</html>
./list.html(視圖模闆):
<dl>
<dd ng-repeat="item in items">{{item}}</dd>
</dl>