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

目录

原理

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

上一篇:2013 duilib入门简明教程 -- 自绘控件 (15)


下一篇:Ubuntu中清理Network下Connect to Server的入口