在AngularJS中,可以使用ngRoute
模块来实现路由功能。下面是一个示例代码,演示如何创建多个路由:
ngRoute
模块:var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'contact.html',
controller: 'ContactController'
})
.otherwise({
redirectTo: '/'
});
});
在上面的代码中,我们定义了三个路由:'/'、'/about'和'/contact'。每个路由都指定了对应的模板和控制器。
Welcome to Home Page
About Us
Contact Us
// HomeController
app.controller('HomeController', function($scope) {
// 控制器逻辑
});
// AboutController
app.controller('AboutController', function($scope) {
// 控制器逻辑
});
// ContactController
app.controller('ContactController', function($scope) {
// 控制器逻辑
});
在这些控制器中,你可以编写对应页面的业务逻辑。
通过href
属性指定路由链接,ng-view
指令会根据路由规则动态加载对应的模板。
这样,你就可以通过点击链接来切换不同的路由和页面了。