O'Reilly書上的偽代碼
var someModule = angular.module('someModule',[...module dependencies]); someModule.config(function($routeProvider){ $routeProvider .when('url',{controller:aController, templateUrl:'/path/to/template'}) .when(...)//other mappings for your app .otherwise(...)//what to do if nothing else matches });
$route被用於URLS到controller和view(HTML模板)之間的鏈接,它會監控$location.url()並試圖對此路徑及對應的路由配置進行映射,使用時需要注入安裝ngroute模塊。
var someModule = angular.module('someModule',['ngRoute']);
舉個詳細的栗子
var app = angular.module('app', ['ngRoute']); app.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'; }); app.controller('otherCtrl',function($scope){ console.log('i am other page'); $scope.title = 'i am other page'; }); app.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'; });
在$route(路由)中,提供了兩個依賴性服務:$location、$routeParams。
$location、$routeParams均可在controller中使用,如上otherDetailCtrl中,可通過$routeParams獲取路由時所傳參數,可通過$location進行路由跳轉。