1. 程式人生 > >AngularJS ui-router (巢狀路由)

AngularJS ui-router (巢狀路由)

  我們都知道,如果使用原生路由的話,Angular的檢視是通過ng-view這個指令進行載入的。比如這樣:<div ng-view></div>。一般,我們都會把這個指令放在index.html這個檔案裡面,然後,通過控制器來載入相應的模板檢視。比如這樣:

var bookStoreApp = angular.module('bookStoreApp', [
    'ngRoute', 'ngAnimate', 'bookStoreCtrls',
]);
bookStoreApp.config(function($routeProvider) {
    $routeProvider.when('/hello', {
        templateUrl: 'tpls/hello.html',
        controller: 'HelloCtrl'
    }).when('/list', {
        templateUrl: 'tpls/bookList.html',
        controller: 'BookListCtrl'
    }).otherwise({
        redirectTo: '/hello'
    })
});

  這是屬於AngularJS的原生路由定義。從表面上看似乎挺方便,沒有什麼太大的問題。但是細想一下,如果說我們有一個網頁,左邊是選單欄,右邊是各個選單所對應的檢視。那麼,如果按照這樣的定義,點選每個選單項,豈不得重新整理整個網頁?而我們想要的只是右邊的檢視重新整理。所以,這就要用到巢狀路由了。

  所謂巢狀路由,就是視圖裡面還可以再巢狀檢視,路由裡還可以再巢狀路由。並且,通過ui-router,可以實現不同檢視之間的引數傳遞。

  ui-router定義路由的時候,與ngRouter不一樣,它是使用.來進行定義的,並且在html標籤裡,不使用ng-view,而是使用ui-view,比如<div ui-view></div>。

ui-router提供了$stateProvider$urlRouterProvider來進行路由定義。

下面的例項演示如何實現路由巢狀:

home.html

建立如下的html頁面:

<div class="jumbotron text-center">
    <h1>Home</h1>
    <p>This page demonstrates
        <span class="text-danger">nested</span>views.
   	</p>
    <a ui-sref=".list" class="btn btn-primary">List</a>
    <a ui-sref=".paragraph" class="btn btn-danger">Paragraph</a>
</div>
<div ui-view></div>

home-list.html

建立如下的html頁面:

<ul>
    <li ng-repeat="topic in topics">{{ topic }}</li>
</ul>

about.html

建立如下的html頁面:

<div class="jumbotron text-center">
    <h1>The About Page</h1>
    <p>This page demonstrates
        <span class="text-danger">multiple</span>and
        <span class="text-danger">named</span>views.</p>
</div>
<div class="row">
    <div class="col-md-6">
        <div ui-view="columnOne"></div>
    </div>
    <div class="col-md-6">
        <div ui-view="columnTwo"></div>
    </div>
</div>

table-data.html

建立如下的html頁面:

<h2>Ice-Creams</h2>
<table class="table table-hover table-striped table-bordered">
    <thead>
        <tr>
            <td>Name</td>
            <td>Cost</td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="topic in topics">
            <td>{{ topic.name }}</td>
            <td>${{ topic.price }}</td>
        </tr>
    </tbody>
</table>

  注意,到目前為止,我們還沒有插入任何AngularJS路由或者其它任何框架。目前我們只是建立了一些頁面片段,我們需要一個佔位或者說父頁面來裝下這些頁面片段。讓我們把這個頁面叫做 index.html.

index.html

用如下內容建立這個html頁面

<!doctype html>
<html ng-app="routerApp">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
    <script src="js/angular.min.js"></script>
    <script src="js/angular-animate.js"></script>
    <script src="js/angular-ui-router.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="navbar-header">
            <a class="navbar-brand" ui-sref="#">AngularUI Router</a>
        </div>
        <ul class="nav navbar-nav">
            <li>
                <a ui-sref="home">Home</a>
            </li>
            <li>
                <a ui-sref="about">About</a>
            </li>
        </ul>
    </nav>
    <div class="container">
        <div ui-view=""></div>
    </div>
</body>
</html>

  在主頁中我們引入了angular.min.js、angular-ui-router.js、angular-animate.js和app.js。在class為container的div中我們建立了一個<div ui-view=""></div>, 該 div 內的 HTML 內容會根據路由的變化而變化。在<a ui-sref="home"></a>中ui-sref 指令連結到特定狀態。

  在app.JS檔案的內容,我們聲明瞭AngularJS模組和路由配置。當頁面載入的時候我們會在index.html中顯示home.html的內容。程式碼如下:

var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
	/*路由重定向 $urlRouterProvider:如果沒有路由引擎能匹配當前的導航狀態,那它就會預設將路徑路由至 home.html, 
	 *這個頁面就是狀態名稱被宣告的地方. */
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'tpls2/home.html'
        })
     /*  nested list with custom controller*/
    .state('home.list', {
        url: '/list',
        templateUrl: 'tpls2/home-list.html',
        controller: function($scope) {
            $scope.topics = ['Butterscotch', 'Black Current', 'Mango'];
        }
    })
    // nested list with just some random string data
    .state('home.paragraph', {
        url: '/paragraph',
        template: 'I could sure use a scoop of ice-cream. '
    })
    .state('about', {
        url: '/about',
        /* view 用在該狀態下有多個 ui-view 的情況,可以對不同的 ui-view 使用特定的 template, controller, resolve data
         絕對 view 使用 '@' 符號來區別,比如 '[email protected]' 表明名為 'columnOne' 的 ui-view 使用了 'about' 狀態的
         模板(template),相對 view 則無*/
        views: {
        	// 無名 view
            '': {
                templateUrl: 'tpls2/about.html'
            },
            // for "ui-view='columnOne'"
            '[email protected]': {
                template: '這裡是第一列的內容'
            },
            // for "ui-view='columnTwo'"
            '[email protected]': {
                templateUrl: 'tpls2/table-data.html',
                controller: 'Controller'
            }
        }
    });
});
routerApp.controller('Controller', function($scope) {
    $scope.message = 'test';
    $scope.topics = [{
        name: 'Butterscotch',
        price: 50
    }, {
        name: 'Black Current',
        price: 100
    }, {
        name: 'Mango',
        price: 20
    }];
});