32-路由

<!-- AngularJS 路由允許我們通過不同的 URL 訪問不同的內容。

通過 AngularJS 可以實現多視圖的單頁Web應用(single page web application,SPA)。

通常我們的URL形式爲 http://runoob.com/first/page,但在單頁Web應用中 AngularJS 通過 # + 標記 實現,例如:

http://runoob.com/#/first
http://runoob.com/#/second
http://runoob.com/#/third

當我們點擊以上的任意一個鏈接時,向服務端請的地址都是一樣的 (http://runoob.com/)。 因爲 # 號之後的內容在向服務端請求時會被瀏覽器忽略掉。 所以我們就需要在客戶端實現 # 號後面內容的功能實現。 AngularJS 路由 就通過 # + 標記 幫助我們區分不同的邏輯頁面並將不同的頁面綁定到對應的控制器上。-->
<html>
    <head>
        <meta charset="utf-8">
        <title>AngularJS 路由實例 - 菜鳥教程</title>
    </head>
    <body ng-app='routingDemoApp'>

        <h2>AngularJS 路由應用</h2>
        <ul>
            <li><a href="#/">首頁</a></li>
            <li><a href="#/computers">電腦</a></li>
            <li><a href="#/printers">打印機</a></li>
            <li><a href="#/blabla">其他</a></li>
        </ul>

        <div ng-view></div>
        <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
        <script src="https://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
        <script>
            angular.module('routingDemoApp',['ngRoute'])
            .config(['$routeProvider', function($routeProvider){
                $routeProvider
                .when('/',{template:'這是首頁頁面'})
                .when('/computers',{template:'這是電腦分類頁面'})
                .when('/printers',{template:'這是打印機頁面'})
                .otherwise({redirectTo:'/'});
            }]);
        </script>


    </body>
</html>
<!-- 
實例解析:

    1、載入了實現路由的 js 文件:angular-route.js。

    2、包含了 ngRoute 模塊作爲主應用模塊的依賴模塊。

    angular.module('routingDemoApp',['ngRoute'])

    3、使用 ngView 指令。

    <div ng-view></div>

    該 div 內的 HTML 內容會根據路由的變化而變化。

    4、配置 $routeProvider,AngularJS $routeProvider 用來定義路由規則。

    module.config(['$routeProvider', function($routeProvider){
        $routeProvider
            .when('/',{template:'這是首頁頁面'})
            .when('/computers',{template:'這是電腦分類頁面'})
            .when('/printers',{template:'這是打印機頁面'})
            .otherwise({redirectTo:'/'});
    }]);

AngularJS 模塊的 config 函數用於配置路由規則。通過使用 configAPI,我們請求把$routeProvider注入到我們的配置函數並且使用$routeProvider.whenAPI來定義我們的路由規則。

$routeProvider 爲我們提供了 when(path,object) & otherwise(object) 函數按順序定義所有路由,函數包含兩個參數:

    第一個參數是 URL 或者 URL 正則規則。
    第二個參數是路由配置對象。

-->
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章