AngularJS 路由
本章節我們將為大家介紹 AngularJS 路由。
AngularJS 路由允許我們通過不同的 URL 訪問不同的內容。
通過 AngularJS 可以實現多視圖的單頁 Web 應用(single page web application,SPA)。
通常我們的 URL 形式為 http://runoob.com/first/page,但在單頁 Web 應用中 AngularJS 通過 #! + 標記 實現,例如:
http://runoob.com/#!/first http://runoob.com/#!/second http://runoob.com/#!/third
注意 Angular1.6 之前的版本是通過 # + 標記 實現路由。
當我們點擊以上的任意一個鏈接時,向服務端請的地址都是一樣的 (http://runoob.com/)。 因為 #! 號之後的內容在向服務端請求時會被瀏覽器忽略掉。 所以我們就需要在客戶端實現 #! 號後麵內容的功能實現。 AngularJS 路由就通過 #! + 標記 幫助我們區分不同的邏輯頁麵並將不同的頁麵綁定到對應的控製器上。
在以上圖形中,我們可以看到創建了兩個 URL: /ShowOrders 和 /AddNewOrder。每個 URL 都有對應的視圖和控製器。
接下來我們來看一個簡單的實例:
AngularJS 實例
嚐試一下 »
實例解析:
1、載入了實現路由的 js 文件:angular-route.js。
2、包含了 ngRoute 模塊作為主應用模塊的依賴模塊。
angular.module('routingDemoApp',['ngRoute'])
3、使用 ngView 指令。
<div ng-view></div>
該 div 內的 HTML 內容會根據路由的變化而變化。
4、配置 $routeProvider,AngularJS $routeProvider 用來定義路由規則。
module.config(['$routeProvider', function($routeProvider){ $routeProvider .when('/',{template:'這是首頁頁麵'}) .when('/computers',{template:'這是電腦分類頁麵'}) .when('/printers',{template:'這是打印機頁麵'}) .otherwise({redirectTo:'/'}); }]);
AngularJS 模塊的 config 函數用於配置路由規則。通過使用 configAPI,我們請求把$routeProvider注入到我們的配置函數並且使用$routeProvider.whenAPI來定義我們的路由規則。
$routeProvider 為我們提供了 when(path,object) & otherwise(object) 函數按順序定義所有路由,函數包含兩個參數:
- 第一個參數是 URL 或者 URL 正則規則。
- 第二個參數是路由配置對象。
路由設置對象
AngularJS 路由也可以通過不同的模板來實現。
$routeProvider.when 函數的第一個參數是 URL 或者 URL 正則規則,第二個參數為路由配置對象。路由配置對象語法規則如下:
$routeProvider.when(url, { template: string, templateUrl: string, controller: string, function 或 array, controllerAs: string, redirectTo: string, function, resolve: object<key, function> });
參數說明:
template:
如果我們隻需要在 ng-view 中插入簡單的 HTML 內容,則使用該參數:
.when('/computers',{template:'這是電腦分類頁麵'})
templateUrl:
如果我們隻需要在 ng-view 中插入 HTML 模板文件,則使用該參數:
$routeProvider.when('/computers', { templateUrl: 'views/computers.html', });
以上代碼會從服務端獲取 views/computers.html 文件內容插入到 ng-view 中。
controller:
function、string或數組類型,在當前模板上執行的controller函數,生成新的scope。
controllerAs:
string類型,為controller指定別名。
redirectTo:
重定向的地址。
resolve:
指定當前controller所依賴的其他模塊。
實例
AngularJS 實例
嚐試一下 »
大兵瑞恩
rya***ng_best@126.com
路由設置對象參數規則:
大兵瑞恩
rya***ng_best@126.com
Ar
che***ev@outlook.com
根據該教程可知,路由有三種設置。
第一種,設置在 Module 的 Config 階段,設置 routeProvider,提供簡單的 template 模板字符串,當被該路徑模式被請求時,將 template 模板字符串渲染在 ng-view 位置。
第二種,設置 templateUrl,且頁麵文件中存在 type為text/ng-template 的模板 js 片段,將會搜索 id 等於 templateUrl 的模板 js,並渲染在 ng-view 的位置。
第三種,設置 templateUrl,如果頁麵文件中不存在與 tempalteUrl 相匹配的 js 模板,則通過相對路徑向服務器請求資源,請求完畢再渲染出來。
Ar
che***ev@outlook.com