angular學習之ngRoute路由機制
ngRoute簡介
路由是AngularJS很重要的一環(huán),它可以把你項目的頁面串聯(lián)起來,構成一個項目,常用的路由有ngRoute和ui-route,我這里先講ngRoute。ngRoute是一個Module,提供路由和深層鏈接所需的服務和指令。
注意一點,和之前的文章不一樣,使用ngRoute之前你需要引入另外一個js文件angular-route.js:
<script src="script/angular.min.js"></script> <script src="script/angular-route.min.js"></script>
ngRoute包含內(nèi)容如下:
| 名稱 | 類型 | 作用 |
|---|---|---|
| ngView | Directive | 路由的不同模板其實都是插入這個元素里 |
| $routeProvider | Provider | 路由配置 |
| $route | Service | 各個路由的url,view,controller |
| $routeParams | Service | 路由參數(shù) |
使用ngRoute的基本流程如下:
- 在需要路由的地方使用ngView來定義視圖模板。
- 在module中注入ngRoute模塊
- 在config中用$routeProvider來對路由進行配置templateUrl,controller,resolve。
- 在每個controller中寫業(yè)務邏輯
- 在controller中可以通過注入$routeParams來獲得url上的參數(shù)
可以看下下面這個例子
color.html
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8"/>
<title></title>
</head>
<script src="script/angular.min.js"></script>
<script src="script/angular-route.min.js"></script>
<body ng-app="color">
<p><a href="#/" rel="external nofollow" rel="external nofollow" >Main</a></p>
<a href="#red" rel="external nofollow" rel="external nofollow" >Red</a>
<a href="#green" rel="external nofollow" rel="external nofollow" >Green</a>
<div ng-view></div>
</body>
<script>
var app = angular.module("color", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "main.html",
controller: 'mainController'
})
.when("/red", {
templateUrl: "red.html",
controller: 'redController'
})
.when("/green", {
templateUrl: "green.html",
controller: 'greenController'
})
.otherwise('/');
});
app.controller('mainController',['$scope',function mainController($scope){
$scope.message='this is main page';
}]);
app.controller('redController',['$scope',function mainController($scope){
$scope.message='this is red page';
}]);
app.controller('greenController',['$scope',function mainController($scope){
$scope.message='this is green page';
}]);
</script>
</html>
red.html (其他頁面類似,就不重復了)
<div style="background: red">
{{message}}
</div>
例子很簡單,我們就只講下路由的配置:
- 使用$routeProvider.when來配置路由的關系,方法接受兩個參數(shù),第一個參數(shù)是url的路徑,第二個參數(shù)是配置url對應的templateUrl和controller。
- $routeProvider.otherwise方法相當于default。
路由模塊化
可能你已經(jīng)注意到了上面的都寫在一起,如果項目越來越大,會不會很頭疼,那么是不是可以把它模塊化,每個模塊都有直接的module,controller,config等。模塊依賴的技術我們之前的module那篇文章已經(jīng)講過,那么就來看下帶有路由的情況下,怎么模塊化。
color.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8"/>
<title></title>
</head>
<script src="script/angular.min.js"></script>
<script src="script/angular-route.min.js"></script>
<script src="red.js"></script>
<script src="green.js"></script>
<script src="main.js"></script>
<body ng-app="color">
<p><a href="#/" rel="external nofollow" rel="external nofollow" >Main</a></p>
<a href="#red" rel="external nofollow" rel="external nofollow" >Red</a>
<a href="#green" rel="external nofollow" rel="external nofollow" >Green</a>
<div ng-view></div>
</body>
<script>
var app = angular.module("color", ["ngRoute","Module.red","Module.main","Module.green"]);
app.config(function ($routeProvider) {
$routeProvider.otherwise('/');
});
</script>
</html>
可以看到我們的color.html文件是不是很簡潔,config的路由配置里只有一行$routeProvider.otherwise方法,但是module卻注入了除ngRoute外的三個module:”Module.red”,”Module.main”,”Module.green”,這其實是把path對應的路由提取成模塊,使用了專門的js來處理它們,看起來和他們對應的模板相對應,我們來看下red.html對應的模塊js:
red.js
angular.module('Module.red', ['ngRoute'])
.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider.when('/red', {
templateUrl: 'red.html',
controller: 'redController'
});
}
])
.controller('redController', [
'$scope',
function ($scope) {
$scope.color='red';
$scope.message = 'This is red page';
}
]);
路由的參數(shù)
那么路由怎么將參數(shù)傳入到模板頁呢?我們把上面的例子改造一下,通過例子來講解:
main.js
angular.module('Module.main', ['ngRoute'])
.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
});
}
])
.controller('mainController', [
'$scope',
function ($scope) {
$scope.message = 'This is main page';
$scope.colors=['blue','yellow','pink'];
}
]);
這里初始化了一個colors的數(shù)組,作為要傳遞的數(shù)據(jù)。
main.html
{{message}}
<br>
<ul>
<li ng-repeat="color in colors">
<a href="#/color/{{color}}" rel="external nofollow" >{{color}}</a>
</li>
</ul>
通過ng-repeat循環(huán)創(chuàng)建a鏈接,數(shù)組的元素通過鏈接傳入。
colorId.js
angular.module('Module.colorId', ['ngRoute'])
.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/color/:colorId', {
templateUrl: 'colorId.html',
controller: 'colorIdController'
});
}
])
.controller('colorIdController', [
'$scope','$routeParams',
function ($scope,$routeParams) {
$scope.color = $routeParams.colorId;
$scope.message = 'This is ' +$routeParams.colorId +' page';
}
]);
這里定義了一個colorId的模塊,通過:colorId來匹配傳入的參數(shù),這里匹配到的是數(shù)組中的元素。例如/color/blue,那么匹配到的就是blue。
colorId.html
<div style="background: {{color}}">
{{message}}
</div>
最后在colorId上呈現(xiàn)出來。
如果是多個參數(shù)可以直接一一接到后面比如/color/:colorId/:year/:month/:day,和后面的參數(shù)也一一匹配,如/color/pink/2017/3/13。
支持*號:/color/:color/largecode/:largecode*/edit匹配/color/brown/largecode/code/with/slashes/edit的話,color將會匹配到brown,largecode將匹配到code/with/slashes。
支持?號:/color/:color/largecode/:largecode?/edit可以匹配匹配/color/brown/largecode/code/edit,largecode將會匹配到code。
/color/:color/largecode/:largecode?/edit可以匹配匹配/color/brown/largecode/edit,largecode將會匹配到空值。
路由中的resolve
一個最常見的情景,頁面跳轉時要加載一些數(shù)據(jù)。有兩種方式可以做到:
- 頁面跳轉后加載,通過controller去控制數(shù)據(jù)的加載,如果時間較長則顯示一個loading的界面,數(shù)據(jù)請求成功后再替換成數(shù)據(jù)界面
- 頁面跳轉前加載,通過路由的resolve去配置。
個人更喜歡跳轉后加載的方式,因為更為友好,所以對resolve不太感冒,但我們還是講下resolve。
resolve是一個map對象:
- map的key是可以注入到controller的可選的依賴項,如果resolve其中依賴項的返回值是promise,那么在controller初始化之前,路由會一直等待直到所有的promise都已經(jīng)resolved或者其中的一個被rejected。如果所有的promise都成功resolved,這些依賴項將可以注入到controller中并同時觸發(fā)$routeChangeSuccess事件,如果其中的一個promise是rejected,那么將會觸發(fā)$routeChangeError事件,并中止路由切換。
- map的value如果是個字符串,那么它會是一個service的別名。如果是一個函數(shù),他的返回值可以被當做依賴注入 到controller中,如果返回值是一個promise,在注入之前必須是resolved的。注意這時候ngRoute.$routeParams還不可用,如果需要使用參數(shù)則需要使用$route.current.params。
看下例子:
news.html
<html>
<head>
<meta charset="uft-8"/>
<title></title>
</head>
<script src="script/angular.min.js"></script>
<script src="script/angular-route.min.js"></script>
<body ng-app="ngst-news">
<div ng-controller="MainController">
<ul>
<li ng-repeat="news in newsAarry">
<a href="#/newsDetail/{{news.id}}" rel="external nofollow" >{{news.title}}</a>
</li>
</ul>
<div ng-view></div>
</div>
</body>
<script src="news.js" charset="UTF-8"></script>
<script src="newsDetail.js" charset="UTF-8"></script>
</html>
news.js
var news = angular.module("ngst-news", ["ngst-newsDetail"]);
news.controller("MainController", ["$scope", function ($scope) {
$scope.newsAarry = [{"id": "1", "title": "遼寧人大副主任王陽 浙江寧波市長盧子躍被免職"},
{"id": "2", "title": "今冬小雨繽紛,荔枝園地濕潤壯旺荔枝果樹,下刀環(huán)剝最狠"},
{"id": "3", "title": "百度任原搜索渠道總經(jīng)理顧國棟為市場執(zhí)行總監(jiān)"}];
}]);
news頁面是一個新聞列表,在列表下面有個ng-view,點擊新聞列表鏈接下面的ng-view進行路由切換。
newsDetails.html
{{message}}
newsDetails.js
var news = angular.module("ngst-newsDetail", ['ngRoute']);
news.config(["$routeProvider",
function ($routeProvider) {
$routeProvider.when("/newsDetail/:newsId", {
templateUrl: 'newsDetail.html',
controller: 'newsDetailController',
resolve: {
content: ['$q', '$timeout', "$route", function ($q, $timeout, $route) {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('新聞詳情 id=' + $route.current.params.newsId);
}, 1000);
return deferred.promise;
}]
}
});
}])
.controller("newsDetailController", ['$scope', 'content',
function ($scope, content) {
$scope.message = content;
}]);
這里使用$route.current.params來獲得參數(shù)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳解angular2采用自定義指令(Directive)方式加載jquery插件
本篇文章主要介紹了詳解angular2采用自定義指令(Directive)方式加載jquery插件 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02
利用Ionic2 + angular4實現(xiàn)一個地區(qū)選擇組件
ionic是一個移動端開發(fā)框架,使用hybird技術,只要使用前端開發(fā)技術就可以開發(fā)出電腦端,安卓端和ios端的站點程序。下面這篇文章主要給大家介紹了關于利用Ionic2 + angular4實現(xiàn)一個地區(qū)選擇組件的相關資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07
angularJS+requireJS實現(xiàn)controller及directive的按需加載示例
本篇文章主要介紹了angularJS+requireJS實現(xiàn)controller及directive的按需加載示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
AngularJS實現(xiàn)分頁顯示數(shù)據(jù)庫信息
這篇文章主要為大家詳細介紹了AngularJS實現(xiàn)分頁顯示數(shù)據(jù)庫信息效果的相關資料,感興趣的小伙伴們可以參考一下2016-07-07

