ng-route模塊中的$routeService監測$location.url()的變化,并將它映射到預先定義的控制器。也就是在客戶端進行URL的路由。var app = angular.module('myApp', ['ngRoute'])? ? .controller('MainController', function($scope) {? ? })? ? .config(function($routeProvider, $locationProvider) {? ? ? $routeProvider? ? ? ? ? .when('/users', {? ? ? ? ? ? ? templateUrl: 'user-list.html',? ? ? ? ? ? ? controller: 'UserListCtrl'? ? ? ? ? })? ? ? ? ? .when('/users/:username', {? ? ? ? ? ? ? templateUrl: 'user.html',? ? ? ? ? ? ? controller: 'UserCtrl'? ? ? ? ? });? ? ? ? // configure html5? ? ? ? $locationProvider.html5Mode(true);? ? });使用 : $location.path 進行跳轉參數使用: $routeParams
UI-Router是Angular-UI提供的客戶端路由框架,它解決了原生的ng-route的很多不足:1. 視圖不能嵌套。這意味著$scope會發生不必要的重新載入。這也是我們在Onboard中引入ui-route的原因。2. 同一URL下不支持多個視圖。這一需求也是常見的:我們希望導航欄用一個視圖(和相應的控制器)、內容部分用另一個視圖(和相應的控制器)。UI-Router提出了$state的概念。一個$state是一個當前導航和UI的狀態,每個$state需要綁定一個URL Pattern。 在控制器和模板中,通過改變$state來進行URL的跳轉和路由$stateProvider? ? .state('contacts', {? ? ? ? url: '/contacts',? ? ? ? template: 'contacts.html',? ? ? ? controller: 'ContactCtrl'? ? })? ? .state('contacts.detail', {? ? ? ? url: "/contacts/:contactId",? ? ? ? templateUrl: 'contacts.detail.html',? ? ? ? controller: function ($stateParams) {? ? ? ? ? ? // If we got here from a url of /contacts/42? ? ? ? ? ? $stateParams.contactId === "42";? ? ? ? }? ? });跳轉:$state.go參數: $stateParams在ui-router中,一個$state下可以有多個視圖,它們有各自的模板和控制器。這一點也是ng-route所沒有的, 給了前端路由極大的靈活性。
$stateProvider? .state('report',{? ? views: {? ? ? 'filters': {? ? ? ? templateUrl: 'report-filters.html',? ? ? ? controller: function($scope){ ... controller stuff just for filters view ... }? ? ? },? ? ? 'tabledata': {? ? ? ? templateUrl: 'report-table.html',? ? ? ? controller: function($scope){ ... controller stuff just for tabledata view ... }? ? ? },? ? ? 'graph': {? ? ? ? templateUrl: 'report-graph.html',? ? ? ? controller: function($scope){ ... controller stuff just for graph view ... }? ? ? }? ? }? })