a.html
<p ui-view='index'></p>
b.html
<p ui-view='content'></p>
c.html
<p>content1</p>
d.html
<p>content2</p>
a.html中綁定事件觸發(fā)content視圖切換到c.html或d.html
$stateProvider的config該怎麼配置
js裡如果手動做切換?
你的問題裡缺少一些必要的上下文信息,所以我只能靠推測或猜來補(bǔ)充完整了
任何SPA 框架的路由系統(tǒng)都是一樣的:每一個路由對應(yīng)著應(yīng)用程式的狀態(tài),而應(yīng)用程式狀態(tài)的變化體現(xiàn)在URLs 的變化上;反之也是,URLs 的變化將會引起路由系統(tǒng)動態(tài)的刷新應(yīng)用程序的狀態(tài)。
在你的例子,路由的入口只有恆定的一個 ui-view='content'
,但卻要不同的視圖(c.html
和 d.html
)動態(tài)的進(jìn)入其中,這就意味著 c.html
和 d.html
要對應(yīng)應(yīng)用程式的不同狀態(tài),路由系統(tǒng)才可以據(jù)此而動態(tài)的更新。
假設(shè)你的例子是這樣的:
當(dāng) /posts/show/c
的時候,ui-view='content'
顯示 c.html
當(dāng) /posts/show/d
的時候,ui-view='content'
顯示 d.html
於是我們才可以對應(yīng)到 ui-router 裡面:
state
是 posts.show
動態(tài)片段,即 URLs 中可變的部分,對應(yīng) state
里的 url
,我把它命名為 :name
view
的入口是 content@posts.show
這樣便足以寫出絕大部分程式碼了:
angular.module('YourApp').config(function ($stateProvider) {
$stateProvider.state('posts.show', {
url: '/show/:name',
views: {
'content@posts.show': {
templateUrl: /* TODO */,
controller: ...
}
}
});
});
唯一剩下的問題是:當(dāng) :name
變化的時候,如何更新 templateUrl
?
之前說過的,URLs 的變化會引發(fā)路由系統(tǒng)更新應(yīng)用程式的狀態(tài),這些變化在路由系統(tǒng)中被保存在 $params
對象中,我們可以用該對象提取變化的部分并生成正確的 templateUrl
。這裡我寫一個助手函數(shù)來做這件事:
angular.module('YourApp').config(function ($stateProvider) {
$stateProvider.state('posts.show', {
url: '/show/:name',
views: {
'content@posts.show': {
templateUrl: getTemplateUrl,
controller: ...
}
}
});
function getTemplateUrl() {
return: 'templates/posts/' + $params.name + '.html';
}
});
ui-router 這個模組,templateUrl
不只是接收字串,也可以接收函數(shù)的回傳值。於是你可以得到:
當(dāng) /posts/show/c
的時候,/posts/show/c
的時候,templateUrl
是 templates/posts/c.html
是 templates/posts/c.html
當(dāng) /posts/show/d
的時候,/posts/show/d
的時候,templateUrl
是 templates/posts/d.html
是 templates/posts/d.html
對應(yīng)的,在你 index
里的導(dǎo)航鏈接就要負(fù)責(zé)切換 /posts/show/:name
的變化,如何產(chǎn)生對應(yīng)動態(tài)片段的連結(jié)在 ui-router 的文檔裡有,自己去找來看吧。
我覺得樓上的人打得太複雜,隨便看個ui-view的 教程不就好了嗎
https://scotch.io/tutorials/a...