angular學(xué)習(xí)之ngRoute路由機(jī)制
ngRoute簡介
路由是AngularJS很重要的一環(huán),它可以把你項(xiàng)目的頁面串聯(lián)起來,構(gòu)成一個(gè)項(xiàng)目,常用的路由有ngRoute和ui-route,我這里先講ngRoute。ngRoute是一個(gè)Module,提供路由和深層鏈接所需的服務(wù)和指令。
注意一點(diǎn),和之前的文章不一樣,使用ngRoute之前你需要引入另外一個(gè)js文件angular-route.js:
<script src="script/angular.min.js"></script> <script src="script/angular-route.min.js"></script>
ngRoute包含內(nèi)容如下:
名稱 | 類型 | 作用 |
---|---|---|
ngView | Directive | 路由的不同模板其實(shí)都是插入這個(gè)元素里 |
$routeProvider | Provider | 路由配置 |
$route | Service | 各個(gè)路由的url,view,controller |
$routeParams | Service | 路由參數(shù) |
使用ngRoute的基本流程如下:
- 在需要路由的地方使用ngView來定義視圖模板。
- 在module中注入ngRoute模塊
- 在config中用$routeProvider來對(duì)路由進(jìn)行配置templateUrl,controller,resolve。
- 在每個(gè)controller中寫業(yè)務(wù)邏輯
- 在controller中可以通過注入$routeParams來獲得url上的參數(shù)
可以看下下面這個(gè)例子
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 (其他頁面類似,就不重復(fù)了)
<div style="background: red"> {{message}} </div>
例子很簡單,我們就只講下路由的配置:
- 使用$routeProvider.when來配置路由的關(guān)系,方法接受兩個(gè)參數(shù),第一個(gè)參數(shù)是url的路徑,第二個(gè)參數(shù)是配置url對(duì)應(yīng)的templateUrl和controller。
- $routeProvider.otherwise方法相當(dāng)于default。
路由模塊化
可能你已經(jīng)注意到了上面的都寫在一起,如果項(xiàng)目越來越大,會(huì)不會(huì)很頭疼,那么是不是可以把它模塊化,每個(gè)模塊都有直接的module,controller,config等。模塊依賴的技術(shù)我們之前的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外的三個(gè)module:”Module.red”,”Module.main”,”Module.green”,這其實(shí)是把path對(duì)應(yīng)的路由提取成模塊,使用了專門的js來處理它們,看起來和他們對(duì)應(yīng)的模板相對(duì)應(yīng),我們來看下red.html對(duì)應(yīng)的模塊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']; } ]);
這里初始化了一個(gè)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'; } ]);
這里定義了一個(gè)colorId的模塊,通過:colorId來匹配傳入的參數(shù),這里匹配到的是數(shù)組中的元素。例如/color/blue,那么匹配到的就是blue。
colorId.html
<div style="background: {{color}}"> {{message}} </div>
最后在colorId上呈現(xiàn)出來。
如果是多個(gè)參數(shù)可以直接一一接到后面比如/color/:colorId/:year/:month/:day,和后面的參數(shù)也一一匹配,如/color/pink/2017/3/13。
支持*號(hào):/color/:color/largecode/:largecode*/edit匹配/color/brown/largecode/code/with/slashes/edit的話,color將會(huì)匹配到brown,largecode將匹配到code/with/slashes。
支持?號(hào):/color/:color/largecode/:largecode?/edit可以匹配匹配/color/brown/largecode/code/edit,largecode將會(huì)匹配到code。
/color/:color/largecode/:largecode?/edit可以匹配匹配/color/brown/largecode/edit,largecode將會(huì)匹配到空值。
路由中的resolve
一個(gè)最常見的情景,頁面跳轉(zhuǎn)時(shí)要加載一些數(shù)據(jù)。有兩種方式可以做到:
- 頁面跳轉(zhuǎn)后加載,通過controller去控制數(shù)據(jù)的加載,如果時(shí)間較長則顯示一個(gè)loading的界面,數(shù)據(jù)請(qǐng)求成功后再替換成數(shù)據(jù)界面
- 頁面跳轉(zhuǎn)前加載,通過路由的resolve去配置。
個(gè)人更喜歡跳轉(zhuǎn)后加載的方式,因?yàn)楦鼮橛押?,所以?duì)resolve不太感冒,但我們還是講下resolve。
resolve是一個(gè)map對(duì)象:
- map的key是可以注入到controller的可選的依賴項(xiàng),如果resolve其中依賴項(xiàng)的返回值是promise,那么在controller初始化之前,路由會(huì)一直等待直到所有的promise都已經(jīng)resolved或者其中的一個(gè)被rejected。如果所有的promise都成功resolved,這些依賴項(xiàng)將可以注入到controller中并同時(shí)觸發(fā)$routeChangeSuccess事件,如果其中的一個(gè)promise是rejected,那么將會(huì)觸發(fā)$routeChangeError事件,并中止路由切換。
- map的value如果是個(gè)字符串,那么它會(huì)是一個(gè)service的別名。如果是一個(gè)函數(shù),他的返回值可以被當(dāng)做依賴注入 到controller中,如果返回值是一個(gè)promise,在注入之前必須是resolved的。注意這時(shí)候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)理顧國棟為市場(chǎng)執(zhí)行總監(jiān)"}]; }]);
news頁面是一個(gè)新聞列表,在列表下面有個(gè)ng-view,點(diǎn)擊新聞列表鏈接下面的ng-view進(jìn)行路由切換。
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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
AngularJS下$http服務(wù)Post方法傳遞json參數(shù)的實(shí)例
下面小編就為大家分享一篇AngularJS下$http服務(wù)Post方法傳遞json參數(shù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03在 Angular 中實(shí)現(xiàn)搜索關(guān)鍵字高亮示例
本篇文章主要介紹了在 Angular 中實(shí)現(xiàn)搜索關(guān)鍵字高亮示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03詳解AngularJS通過ocLazyLoad實(shí)現(xiàn)動(dòng)態(tài)(懶)加載模塊和依賴
本篇文章主要介紹了詳解AngularJS通過ocLazyLoad實(shí)現(xiàn)動(dòng)態(tài)(懶)加載模塊和依賴 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-03-03AngularJS 仿微信圖片手勢(shì)縮放的實(shí)例
這篇文章主要介紹了AngularJS 仿微信圖片手勢(shì)縮放的實(shí)例的相關(guān)資料,希望大家通過本文實(shí)現(xiàn)這樣的功能,需要的朋友可以參考下2017-09-09使用AngularJS來實(shí)現(xiàn)HTML頁面嵌套的方法
這篇文章主要介紹了使用AngularJS來實(shí)現(xiàn)HTML頁面嵌套的方法,主要用到了AngularJS中的ng-include指令,需要的朋友可以參考下2015-06-06通過angular CDK實(shí)現(xiàn)頁面元素拖放的步驟詳解
這篇文章主要給大家介紹了關(guān)于如何通過angular CDK實(shí)現(xiàn)頁面元素拖放的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用angular具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Angular 4 依賴注入學(xué)習(xí)教程之FactoryProvider的使用(四)
這篇文章主要給大家介紹了關(guān)于Angular 4 依賴注入之FactoryProvider使用的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Angular4具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-06-06