angularjs router在哪一层

2025-05-20 20:35:50
推荐回答(1个)
回答1:

首先给大家介绍angular-ui-router的基本用法。
如何引用依赖angular-ui-router
?

1
2
3
4

angular.module('app',["ui.router"])
.config(function($stateProvider){
$stateProvider.state(stateName, stateCofig);
})

$stateProvider.state(stateName, stateConfig)
stateName是string类型
stateConfig是object类型
//statConfig可以为空对象
$stateProvider.state("home",{});
//state可以有子父级
$stateProvider.state("home",{});
$stateProvider.state("home.child",{})
//state可以是链式的
$stateProvider.state("home",{}).state("about",{}).state("photos",{});
stateConfig包含的字段:template, templateUrl, templateProvider, controller, controllerProvider, resolve, url, params, views, abstract, onEnter, onExit, reloadOnSearch, data
$urlRouteProvider
$urlRouteProvider.when(whenPath, toPath)
$urlRouterProvider.otherwise(path)
$urlRouteProvider.rule(handler)
$state.go
$state.go(to, [,toParams],[,options])
形参to是string类型,必须,使用"^"或"."表示相对路径;
形参toParams可空,类型是对象;
形参options可空,类型是对象,字段包括:location为bool类型默认true,inherit为bool类型默认true, relative为对象默认$state.$current,notify为bool类型默认为true, reload为bool类型默认为false
$state.go('photos.detail')
$state.go('^')到上一级,比如从photo.detail到photo
$state.go('^.list')到相邻state,比如从photo.detail到photo.list
$state.go('^.detail.comment')到孙子级state,比如从photo.detail到photo.detial.comment
ui-sref
ui-sref='stateName'
ui-sref='stateName({param:value, param:value})'
ui-view
==没有名称的ui-view

?

1
2
3
4


$stateProvider.state("home",{
template: "

hi

"
})

或者这样配置:

?

1
2
3
4
5
6
7

$stateProvider.state("home"{
views: {
"": {
template: "

hi

"
}
}
})

==有名称的ui-view

?

1
2
3
4
5
6
7
8


$stateProvider.state("home",{
views: {
"main" : {
template: "

hi

"
}
}
})

==多个ui-view

?

1
2
3
4
5
6
7
8



$stateProvider.state("home",{
views: {
"":{template: "

hi

"},
"data": {template: "
data
"}
}
})

项目文件结构
node_modules/
partials/
.....about.html
.....home.html
.....photos.html
app.js
index.html
创建state和view
app.js

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

var photoGallery = angular.module('photoGallery',["ui.router"]);
photoGallery.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home',{
url: '/home',
templateUrl: 'partials/home.html'
})
.state('photos',{
url: '/photos',
templateUrl: 'partials/photos.html'
})
.state('about',{
url: '/about',
templateUrl: 'partials/about.html'
})
})

index.html
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19









Welcome













state之间的跳转

index.html
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23




以上通过ui-sref属性完成state之间的跳转。
多个view以及state嵌套
有时候,一个页面上可能有多个ui-view,比如:
?

1
2




假设,以上页面属于一个名称为parent的state中。
我们知道在ui-router中,一个state大致是这样设置的:
?

1
2




所有state下views下的所有键值对(类似 "body@content":{templateUrl: 'partials/photos.html'})都被放到一个键值集合中。而ui-view的工作原理就是根据自己的属性值,到这个键值集合中去找匹配的键,找到就把对应的页面显示出来。
点击header对应的页面链接,可能会跳转到另外的子页面出现在
这个位置。这时候页面出现了子父关系,而每个页面都属于某个state,这样state间就出现了子父关系。这些跳转的子页面,在路由设置中,可能被称为parent.son1, parent.son2...这就是state的嵌套。