ionic中路由管理介紹:
在單頁應(yīng)用中,路由的管理是很重要的環(huán)節(jié)凸丸。ionic.js沒有使用AngularJS內(nèi)置的ng-route路由,而是選擇了AngularUI項(xiàng)目的ui-router模塊。
ui-router的核心理念是將子視圖集合抽象為一個(gè)狀態(tài)機(jī),導(dǎo)航意味著狀態(tài)的切換捅僵。在不同的狀態(tài)下,ionic.js渲染對應(yīng)的子視圖(動態(tài)加載的HTML片段)就實(shí)現(xiàn)了路由導(dǎo)航的功能眨层。
路由設(shè)置
模塊導(dǎo)航用< ion-tabs class=”tabs-bottom”>
$stateProvider .state('tab', {
? ? ? ? ? // cache: false,//是否緩存
? ? ? ? ?url: "/tab/event", ?
? ? ? ? ?abstract:true,//默認(rèn)加載
? ? ? ? ?templateUrl: "templates/event.html"http://模板
})
這樣模板會默認(rèn)加載到ion-nav-view中庙楚,也可以指定加載到某個(gè)ion-nav-view中,使用name屬性
//對應(yīng)的路由寫法是
$stateProvider .state('tab', {
? ? ? ? ?url: "/tab/event",
? ? ? ? ?views:{
? ? ? ? ? ? ? ? ? ?"viewType":{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //viewType與ion-nav-view的name屬性對應(yīng)谐岁,如果dom中沒有name屬性值是viewType的ion-nav-view醋奠,那很有可能不會渲染模板頁面
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? templateUrl: "templates/event.html", ? //模板
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? controller:'controller_events_list'//controller
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?} ?
})
ionic 也支持url參數(shù)
url: "/tab/event/:id/:num"
參數(shù)按順序加到url上
注意:引用url的時(shí)候必須給足對應(yīng)的參數(shù)榛臼,否則路由會跳到空白頁,或者出現(xiàn)其他異常
href="#/school/0/0"
$stateParams獲取url參數(shù)
在controller中注入$stateParams
以上面的為例窜司,取id時(shí)調(diào)用$stateParams.id沛善,同理取num就是$stateParams.num
頁面跳轉(zhuǎn)方法
標(biāo)簽的href
href="#/tab"
js跳轉(zhuǎn)
$location.path("/tab");
要注意在controller里先注入location也可以使用window,同樣的塞祈,使用前需要依賴注入
$window.location.assign(url);
使用$window需要加#號
父子路由
在布局頁面里金刁,通常會有一組頁面是同級的,像登錄议薪、注冊尤蛮、找回密碼。習(xí)慣上希望給這三個(gè)頁面建立一個(gè)同級的邏輯關(guān)系斯议。這里涉及parent.child寫法产捞。
比如下面的代碼:
/auth是父級總管,無法加載auth.login還是其他auth.xx哼御,都會默認(rèn)加載/auth的模板內(nèi)容坯临,這里我設(shè)置成了”“,模板不包含內(nèi)容恋昼。如果/auth中有內(nèi)容看靠,則是/auth開頭的頁面共用的。
//登錄相關(guān)
.state('auth', {
? ? ? ? ?url: '/auth',
? ? ? ? ?views:{
? ? ? ? ? ? ? ? ? ? 'otherPage':{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?templateUrl: ""
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ?}
})
//登錄界面
.state('auth.login', {
? ? ? ? ? ? ? ? url: '/login',
? ? ? ? ? ? ? ? views:{
? ? ? ? ? ? ? ? ? ? ? ?'otherPage':{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?templateUrl: "login.html",
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?controller:'controller_login'
? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? }
})
//注冊
.state('auth.register', {
? ? ? ? ? ? ? url: '/register',
? ? ? ? ? ? ? views:{
? ? ? ? ? ? ? ? ? ? ?'otherPage':{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?templateUrl: "register.html",
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?controller:"controller_register"
? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? }?
})
另外液肌,如果當(dāng)前路徑是/auth時(shí)挟炬,去加載/auth/register這樣的子頁面,不會渲染成功嗦哆。雖然會觸發(fā)$stateChangeSuccess谤祖,但沒有渲染模板,dom不會改變吝秕。
訪問除路由外地址泊脐,可以定向訪問登錄或者其他頁面。
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/auth/login');