今天学了ui-router,从慕课以及自己手动敲代码,感受到了它的魅力,记得假期做过一个图书管理系统的练习,那个时候用的是iframe来实现刷新,现在看来,觉得当时还是太嫩了,进入主题吧
首先说一下为什么不使用ng-router的原因吧,我从网上学习以及找到的资料给出的解释基本上都一样,总结为:因为UI-Router有两个重要的特性:1.多样化视图 2.嵌入式视图,在实际操作中,我们总会给一个html分不同的区域,有菜单栏或者导航栏,主体内容,页脚等等,嵌入式视图就是让不同的视图同时展现或者嵌入到另一个视图中,我写了个小demo,只是为了让自己体验一下ui-router而已,写的并不规范
app.js的部分代码:1
2
3
4
5
6
7var routerApp = angular.module('routerApp', [ 'ui.router', 'ngGrid',
                                              'BookListModule', 'BookDetailModule' ]);
routerApp.run(function($rootScope, $state, $stateParams) {
	$rootScope.$state = $state;
	$rootScope.$stateParams = $stateParams;
});
app.js的配置路由代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37routerApp.config(function($stateProvider, $urlRouterProvider) {
	//运行时找不到想要的状态就会自动的进入index
	$urlRouterProvider.otherwise('/index');
	$stateProvider
	//state后紧跟的那个是一个状态,可以通过ui-sref指令转变状态,例如<a ui-sref="second">二</a>
	.state('index',{
		//url即地址栏的内容,当用户浏览到/index时会找到他需要的视图
		url: '/index',
		//存在多个view时使用这种写法
		views:{
			'':{
				templateUrl: 'tpls/loginForm.html'
			},
		//@符号用在此处代表在index下存在的模块,例如我写的,在index下存在:<a ui-sref="x1">1</a><a ui-sref="x2">2</a> <a ui-sref="x3">3</a>
			'x1@index':{
				templateUrl: 'tpls/first.html'
			},
			'x2@index':{
				templateUrl: 'tpls/second.html'
			},
			'x3@index':{
				templateUrl:'tpls/three.html'
			}
		}
	})
	.state('second',{
		url: '/second',
		templateUrl: 'tpls/three.html'
	})
	.state('three',{
		url: '/three',
		templateUrl: 'tpls/first.html'
	})
})
通过ui-router我们可以实现菜单与内容的分离,这样更好操控不同区域