我现在将其用作解决方案,并且会对替代方案感兴趣!
1)创建一个通用模板,它将加载到控制器中并动态查看:
<div ng-controller="controller" ng-include src="templateUrl"></div>
在这个例子中,我把这个视图放在/www/shared/dynamic-controller.html
2) 创建一个控制器,检查路由参数以确定要加载哪个控制器和视图:
angular.module('appName').
controller('ArtistsDynamicRouteController', ['$scope', '$controller', '$routeParams', function($scope, $controller, $routeParams) {
if(/^\d+$/.test($routeParams.pageOrId)) {
// when pageOrId is a page (number) we want to load the ArtistsIndexController
$scope.controller = $controller('ArtistsIndexController', { $scope: $scope }).constructor;
$scope.templateUrl = '/www/artists/index.html';
} else {
// when pageOrId is an id (non-number) we want to load the ArtistsProfileController
$scope.controller = $controller('ArtistsProfileController', { $scope: $scope }).constructor;
$scope.templateUrl = '/www/artists/profile.html';
}
}]);
3) 无论参数类型如何,都使用一条路由:
// handles both /artists/2 and /artists/username
$routeProvider.when("/artists/:pageOrName", {
templateUrl: "/www/shared/dynamic-controller.html",
controller: "ArtistsDynamicRouteController"
});