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 ... } } } })