AngularJS支持多级路由的方式是通过使用UI-Router模块来实现。下面是一个使用UI-Router实现多级路由的代码示例:
首先,确保已经引入了angular.js
和ui-router.js
库文件。
在应用的主模块中,添加对ui.router
模块的依赖。
var app = angular.module('myApp', ['ui.router']);
$stateProvider
定义各个路由状态。app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
})
.state('about.details', {
url: '/details',
templateUrl: 'about-details.html',
controller: 'AboutDetailsController'
})
.state('contact', {
url: '/contact',
templateUrl: 'contact.html',
controller: 'ContactController'
});
});
在上述代码中,我们定义了四个路由状态,分别是home
、about
、about.details
和contact
。其中,about.details
是about
的子状态。
app.controller('HomeController', function($scope) {
// 控制器逻辑
});
app.controller('AboutController', function($scope) {
// 控制器逻辑
});
app.controller('AboutDetailsController', function($scope) {
// 控制器逻辑
});
app.controller('ContactController', function($scope) {
// 控制器逻辑
});
ui-sref
指令来创建路由链接。
在上述代码中,我们使用ui-sref
指令来指定路由状态,点击链接时将会触发路由跳转。
希望以上示例能帮助到你!