前端之家收集整理的这篇文章主要介绍了
学习 ui-router (三):多个命名的视图,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
转自:@L_301_0@
参考原文:https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views
可以给ui-view
指定名称,这样一个模板中就可以有多个ui-view
。假设您有一个应用,需要动态填充graph
、table data
和filters
,像下面这样:
当您需要使用多视图时,需要用到状态的views
属性,views
属性值是一个对象。
设置views
属性将覆盖覆盖的template
属性
如果在状态中定义了views
属性,那么状态中的templateUrl
、template
和templateProvider
属性将被忽略。
示例 - 名称匹配
views
的属性key
应该对应的ui-view
的名称、像下面这样:
1
2
3
4
5
6
|
<body>
<div ui-view="filters">
</div>
"tabledata">
"graph">
</div>
</body>
|
1
2
3
4
5
6
7
8
|
$stateProvider
.state(
'report',{
views: {
'filters': { ... templates and/or controllers ... },
'tabledata': {},153)">'graph': {},
}
})
|
然后views
中的每一个 view 都可以设置自身的模板属性(template
,templateUrl
,templateProvider
) 和控制器属性(controller
,controllerProvider
)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
'filters': {
templateUrl:
'report-filters.html',
controller:
function($scope){ ... controller stuff just
for filters view ... }
},153)">'tabledata': {
templateUrl:
'report-table.html',204)">for tabledata view ... }
},153)">'graph': {
templateUrl:
'report-graph.html',204)">for graph view ... }
},
}
})
|
视图名称 - 相对命名与绝对命名
在定义views
属性时,如果视图名称中包含@
,那么视图名称就是绝对命名的方式,否则就是相对命名的方式。相对命名的意思是相对于父模板中的ui-view
,而绝对命名则指定了相对于哪个状态的模板。
在 ui-router 内部,views
属性中的每个视图都被按照viewname@statename
的方式分配为绝对名称,viewname
是目标模板中的ui-view
对应的名称,statename
是状态的名称,状态名称对应于一个目标模板。@
前面部分为空表示未命名的ui-view
,@
后面为空则表示相对于根模板,通常是 index.html。
例如,上面的例子可以写成如下方式:
1
2
3
4
5
6
7
|
.state(
views: {
'filters@': { },
'tabledata@': { },153)">'graph@': { }
}
})
|
注意,这样的写法,视图的名称指定为绝对的名字,而不是相对的名字。这样 ‘filters’,’tabledata’和’graph’三个视图将加载到根视图的模板中(由于没有父状态,则根模板就是index.html)。
绝对命名的方式可以让我们完成一些强大的功能,让我们假设我们有几个模板设置(这里仅仅作为实例演示,有些不现实的地方),像下面这样:
1
2
3
4
5
|
<!-- index.html (root unnamed template) -->
<body ng-app>
<div ui-view>
</div>
@H_307_ 403@<!-- contacts.html plugs in here -->
|
<!-- contacts.html -->
<h1>My Contacts
</h1>
"detail">
</div>
|
1
2
3
|
<!-- contacts.detail.html -->
<h1>Contacts Details
"info">
</div>
|
让我们来看看在contacts.detail
状态中,相对命名和绝对命名的各种使用方式,请注意,一旦使用了@
则表示绝对命名的方式。
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
37
38
|
'contacts',{
@H_307_ 403@// 根状态,对应的父模板则是index.html
@H_307_ 403@// 所以 contacts.html 将被加载到 index.html 中未命名的 ui-view 中
templateUrl:
'contacts.html'
})
.state(
'contacts.detail',{
views: {
@H_307_ 403@// 嵌套状态,对应的父模板是 contacts.html
@H_307_ 403@// contacts.html 中 <div ui-view='detail'/> 将对应下面
"detail" : { },
@H_307_ 403@// 对应 contacts.html 中的未命名 ui-view <div ui-view/>
"" : { },
@H_307_ 403@// 对应 contacts.detail.html 中 <div ui-view='info'/>
"info@contacts.detail" : { }
@H_307_ 403@// 对应 contacts.html 中 <div ui-view='detail'/>
"detail@contacts" : { }
@H_307_ 403@"@contacts" : { }
@H_307_ 403@// 对应 index.html 中 <div ui-view='status'/>
"status@" : { }
@H_307_ 403@// 对应 index.html 中 <div ui-view/>
"@" : { }
});
|
你将发现,不仅仅可以在同一状态设置多个视图,而且祖先状态可以由开发者自由控制:)。