[AngularJS] AngularJS系列(2) 中級篇之路由

目錄html

 

原理

ng的route本質是監聽hashchange事件.git

在angular-route中angularjs

    $rootScope.$on('$locationChangeStart', prepareRoute);
    $rootScope.$on('$locationChangeSuccess', commitRoute);

 

在ui-router中github

      listener = listener || $rootScope.$on('$locationChangeSuccess', update);

...    scope.$on('$stateChangeSuccess', function() {
          updateView(false);
        });
...

 

angular-route

Hello Worldapi

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/angular-route.min.js"></script>
</head>
<body>
    <a href="#index">index</a>
    <a href="#home">home</a>
    <div ng-view></div>
    <script>
        angular.module('myApp', ['ngRoute'], ['$routeProvider', function ($route) {
            $route.when('/index', { template: 'Index' })
                .when('/home', { template: 'Home' })
                .otherwise('index');
        }]);
    </script>
</body>
</html>

以上爲最簡單的ngRoute Hello Worldpromise

 

可參考官方API:app

https://docs.angularjs.org/api/ngRouteide

 

這裏再展現1個稍微完整點的Demoui

    <div ng-controller="MainController">
        Choose:
        <a href="#Book/Moby">Moby</a> |
        <a href="#Book/Moby/ch/1">Moby: Ch1</a> |
        <a href="#Book/Gatsby">Gatsby</a> |
        <a href="#Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
        <a href="#Book/Scarlet">Scarlet Letter</a><br />

        <div ng-view></div>

        <hr />

        <pre>$location.path() = {{$location.path()}}</pre>
        <pre>$route.current.template = {{$route.current.template}}</pre>
        <pre>$route.current.params = {{$route.current.params}}</pre>
        <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
        <pre>$routeParams = {{$routeParams}}</pre>
    </div>
    <script>
        angular.module('myApp', ['ngRoute'])
            .controller('MainController', function ($scope, $route, $routeParams, $location) {
                $scope.$route = $route;
                $scope.$location = $location;
                $scope.$routeParams = $routeParams;
            })
            .controller('BookController', function ($scope, $routeParams) {
                $scope.name = 'BookController';
                $scope.params = $routeParams;
            })
            .controller('ChapterController', function ($scope, $routeParams) {
                $scope.name = 'ChapterController';
                $scope.params = $routeParams;
            })
            .config(function ($routeProvider, $locationProvider) {
                $routeProvider
                 .when('/Book/:bookId', {
                     template: 'controller: {{name}}<br />Book Id: {{params.bookId}}<br />',
                     controller: 'BookController',
                     resolve: {
                         // I will cause a 1 second delay
                         delay: function ($q, $timeout) {
                             var delay = $q.defer();
                             $timeout(delay.resolve, 1000);
                             return delay.promise;
                         }
                     }
                 })
                .when('/Book/:bookId/ch/:chapterId', {
                    template: 'controller: {{name}}<br />Book Id: {{params.bookId}}<br />Chapter Id: {{params.chapterId}}',
                    controller: 'ChapterController'
                });
            });
    </script>

 

ui-router

Hello Worldurl

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/angular-ui-router.min.js"></script>
    <style>
        .active {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <a ui-sref="hello" ui-sref-active="active">Hello</a>
    <a ui-sref="about" ui-sref-active="active">About</a>
    <div ui-view></div>
    <script>
        angular.module('myApp', ['ui.router'], ['$stateProvider', function ($stateProvider) {
            var helloState = {
                name: 'hello',
                url: '/hello',
                template: '<h3>hello world!</h3>'
            }

            var aboutState = {
                name: 'about',
                url: '/about',
                template: '<h3>Its the UI-Router hello world app!</h3>'
            }

            $stateProvider.state(helloState).state(aboutState);
        }]);
    </script>
</body>
</html>

以上展現了ui-router基本的用法

 

事件

和ngRoute相同的是,angular-route服務會在不一樣的狀態生命週期lifecycle裏啓動某些事件events。監聽$scope對象即可以捕獲這些事件而後採起不一樣的響應或者操做。以下的事件將會在$rootScope上觸發,所以在任何$scope對象上均可以監聽到這些事件。

狀態改變事件

$scope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams), { // 若是須要阻止事件的完成 evt.preventDefault();});

能夠觸發的事件包括:

stateChangeStart

當狀態改變開始的時候被觸發

$stateChangeSuccess

當狀態改變成功後被觸發

$stateChangeError

當狀態改變遇到錯誤時被觸發,錯誤一般是目標沒法載入,須要預載入的數據沒法被載入等。

視圖載入事件

視圖載入階段ui-router也提供了一些事件

$viewContentLoading

當視圖正在被載入且在DOM被渲染以前觸發。

$scope.$on('$viewContentLoading', function(event, viewConfig){ // 獲取任何視圖設置的參數,以及一個特殊的屬性:viewConfig.targetView});
$viewContentLoaded

當視圖被載入且DOM已經渲染完成後被觸發。

 

在事件中,再多說2句:

在源碼中的3151行,定義了路由跳轉方法.

    $state.transitionTo = function transitionTo(to, toParams, options) {

在方法中,ui-router 調用$rootScope.$broadcast,進行了廣播事件.

 

而$broadcast,$emit以及$on不是本節重點內容,這裏作簡單介紹:

$broadcast:向當前和子scope中 觸發事件.

$emit:向當前和父scope中 觸發事件

$on:在當前scope中 定義事件

 

一樣的,在ngRoute中,也定義了一些事件

如:$routeChangeStart、$routeChangeSuccess、$routeChangeError 

 

 

深度路由(嵌套路由)

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/angular-ui-router.min.js"></script>
</head>
<body>
    <h1>深度路由</h1>
    <div ui-view></div>
    <script>
        angular.module('myApp', ['ui.router'], ['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
            $stateProvider.state("PageTab", {
                url: "/PageTab",
                template: '<span style="width:100px" ui-sref=".Page1"><a href="#">Page-1</a></span><span style="width:100px" ui-sref=".Page2"><a href="#">Page-2</a></span><span style="width:100px" ui-sref=".Page3"><a href="#">Page-3</a></span> <div ui-view/>'
            })
            .state("PageTab.Page1", {
                url: "/Page1",
                template: "Page-1"
            })
            .state("PageTab.Page2", {
                url: "/Page2",
                template: "Page-2"
            })
            .state("PageTab.Page3", {
                url: "/Page3",
                template: "Page3"
            });
            $urlRouterProvider.otherwise('PageTab');
        }]);
    </script>
</body>
</html>

 

可參考:

ui-router GitHub(https://github.com/angular-ui/ui-router/wiki)

 

本文地址:http://www.cnblogs.com/neverc/p/5907693.html

相關文章
相關標籤/搜索