由于angular内置的路由机制那个ng-router存在一些缺陷,不能很好的实现多视图与嵌套视图,所以一般都会选择angularUI提供的ui-router来代替ng-router。
ui-router中的一些指令:
ui.router在创建路由时,会实例化一个state对象,并存储在states集合里面;每个state对象都有一个state.name进行唯一标识(如:“main”)
ui.router提供了一个指令“ui-sref”来解决循环遍历rules的问题
<a ui-sref="main" ></a>
当点击<a>标签时,会直接跳到“main”state,而不是循环遍历rules;跳到对应的state后,ui.router会改变hash值,所以会触发“$locationChangeSuccess”事件,然后执行回调。
$stateProvider.state('state1',{
url: '/',
template: {<p>this is state one</p>}
}).state('state2',{
url: '/main',
template: {<p>this is state2</p>}
})
ui-router的最大特点是可以实现多视图与嵌套视图
所谓多视图,就是一个页面中可以显示多个动态变化的不同区域。
多视图的一个例子:
$stateProvider.state('main.stateOne',{
url: '/state:[0-9]',
view: {
'@main': {temp;ate: <div>this is stateOne</div>},
//模板内容会被安插到福路由main模板的匿名视图下(ui-view)
'state2@': {template: <div>this is stateTwo</div>},
//模板内容会被安插到跟路由模板名为“state1”的视图下(ui-wview=“state1”)
'state3@main': {template: <p>this is stateThree</p>}
//模板内容会被安插到福路由(main)模板名为“state3”的视图下
}
});
views 用来显示多个视图,它的值为: “ 视图名@ 状态名 ”
视图名是“ui-view=‘state1’”中的state1,也可以是空字符串或者省略,代表匿名视图;
状态名默认情况下是父路由的state.name(即父路由的状态名),也可以是空字符串,表示顶层rootState(最外层的状态名),还可以是该视图的任意祖先的state.name;
所谓嵌套视图,就是在页面中某个动态变化的区域中,嵌套这另一个可以动态变化的区域。
<div ui-view="parentView>
Parent view
<div ui-view="childView">Child view</div>
</div>
参考文章:Angular路由深入浅出(五)