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

來源:互聯網
上載者:User

標籤:

目錄

  • 原理
  • angular-route
  • ui-router
    • 事件
    • 深度路由

 

原理

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

在angular-route中

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

 

在ui-router中

      listener = listener || $rootScope.$on(‘$locationChangeSuccess‘, update);...    scope.$on(‘$stateChangeSuccess‘, function() {          updateView(false);        });...

 

angular-route

Hello World

<!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 World

 

可參考官方API:

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

 

這裡再展示1個稍微完整點的Demo

    <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 World

<!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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.