code-prettify

2014年8月7日 星期四

AngularJS - angular-ui-router 實現 Nested Views 及 Multiple Views

在試著使用 AngularJS 實作 Kuroneko Idle Game 時遇到了問題,
ngRoute 不支持 巢狀 View 及多重 View 的實現。
幸好在 Google 上找到了救兵 ui-router,以下是兩種寫法的差別。

ngRoute 寫法:
app.js config:
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}])
index.html:
<ul class="menu">
<li><a href="#/view1">view1</a></li>
<li><a href="#/view2">view2</a></li>
</ul>
<div ng-view></div>
ui-router 寫法:
app.js config:
config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to
$urlRouterProvider.otherwise("/main");
//
// Now set up the states
$stateProvider
.state('main', {
url: "/main",
templateUrl: "partials/main.html"
})
.state('main.view1', {
url: "/view1",
templateUrl: "partials/partial1.html",
controller: "MyCtrl1"
})
.state('main.view2', {
url: "/view2",
templateUrl: "partials/partial2.html",
controller: "MyCtrl2"
});
}])
index.html:
<div ui-view></div>
main.html (新增):
<ul class="menu">
<li><a ui-sref="main.view1">view1</a></li>
<li><a ui-sref="main.view2">view2</a></li>
</ul>
<div ui-view></div>
<div>Angular seed app: v<span app-version></span></div>
這麼一來就完成了巢狀 View 的實作。

Reference
GitHub - angular-ui/ui-router

沒有留言:

張貼留言