######$route被用於URLS到controller和view(HTML模板)之間的連接,它會監控$location.url()並試圖對此路徑及對應的路由配置進行映射,使用時須要安裝ngroute模塊:css
在模板主頁header上添加:html
<pre><code> <script src="../js/angular-route.min.js"></script></code></pre>angularjs
index.html:bootstrap
<pre></code> <!doctype html> <html xmlns:ng="http://angularjs.org" ng-app='app' ng-csp="" scroll id="ng-app"> <head> <meta charset="UTF-8"> <title>angularjs route</title> <link rel="stylesheet" href="../css/bootstrap.css"/> <script src="../js/angular.min.js"></script> <script src="../js/angular-animate.min.js"></script> <script src="../js/angular-route.min.js"></script> <script src="../js/main.js"></script> </head> <body> <div class="header"> <a href="#/">主頁</a><a href="#/other">其餘頁</a> </div> <div ng-view class="main"></div> </body> </html> </code></pre>app
other.html:ide
<pre><cdoe><h1>{{title}}</h1></code></pre>url
home.html:code
<pre><cdoe><h1>{{title}}</h1></code></pre>xml
使用方式爲,在main.js中添加:htm
<pre><code> var app = angular.module('app', [ 'ngRoute' ]) .config(function ($routeProvider){ $routeProvider .when('/other', { controller: 'otherCtrl', templateUrl: 'content/views/other.html', publicAccess: true }) .when('/', { controller: 'homeCtrl', templateUrl: 'content/views/home.html' }) .when('/other/:id', { controller: 'otherDetailCtrl', templateUrl: 'content/views/otherDetail.html', publicAccess: true }) .otherwise({ redirectTo: '/' }); } app.controller('homeCtrl',function($scope,$http){ console.log('i am home page'); $scope.title = 'i am home page'; }).controller('otherCtrl',function($scope){ console.log('i am other page'); $scope.title = 'i am other page'; }).controller('otherDetailCtrl',function($scope, $routeParams, $location){ var id = $routeParams.id; if(id == 0) { $location.path('/other'); } console.log('i am otherDetailCtrl page'); $scope.title = 'i am otherDetailCtrl page'; }); </code></pre>
當打開index.html時,會自動打開'/',當點擊導航中「主頁」、「其餘頁」時,會進行頁面切換。
在$route(路由)中,提供了兩個依賴性服務:$location、$routeParams; $location、$routeParams都可在controller中使用,如上otherDetailCtrl中,可經過$routeParams獲取路由時所傳參數,可經過$location進行路由跳轉。