ngRoute模块是angularjs自带的路由模块,ui.router是一个第三方路由模块,接下来将对两者进行一个对比:
ng-router(angular-router.js) ng-view ngRoute模块 $routeProvider服务 .when() .otherwise();
ui-router(angular-ui-router.js) ui-view ui.router模块 $stateProvider服务 .state() ,$urlRouterProvider服务 .otherwise();
ng-router:
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<!-- html -->
<ul class="menu">
<li><a href="#/view1">view1</a></li>
<li><a href="#/view2">view2</a></li>
</ul>
<div ng-view></div> //js
angular.module('myApp', ['ngRoute'])
.config(['$locationProvider', '$routeProvider',function($locationProvider, $routeProvider){
$locationProvider.html5Mode(false).hashPrefix('');
$routeProvider
.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
})
.when('/view2', {
templateUrl: 'view2/view2.html',
controller: 'View2Ctrl'
})
.otherwise({redirectTo: '/view1'});
}])
ui-router:
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script> <!--html-->
<ul class="menu">
<li><a ui-sref="state1">state1</a></li>
<li><a ui-sref="state2">state2</a></li>
</ul>
<div ui-view></div> //js
angular.module('myApp', ['ui.router'])
.config(['$stateProvider','$urlRouterProvider',function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/state2');
// ui-router state配置
$stateProvider.state('state1',{
url: "/state1",
templateUrl: "view1/view1.html",
controller: 'View1Ctrl'
}).state('state2',{
url: "/state2",
templateUrl: 'view2/view2.html',
controller: 'View2Ctrl'
});
}])