Javascript AngularJS regex路由相似的url以加载不同的控制器和视图

Javascript AngularJS regex路由相似的url以加载不同的控制器和视图,javascript,angularjs,routes,Javascript,Angularjs,Routes,我有一个类似的路由,应该根据参数是否为数字加载不同的视图和控制器。例如: /artists/2应ArtistsIndexController查看/www/artists/index.html /artists/name应ArtistsProfileController查看/www/artists/profile.html 理想情况下,我会使用以下内容: $routeProvider.when("/artists/:page", { templateUrl: "/www/artists/i

我有一个类似的路由,应该根据参数是否为数字加载不同的视图和控制器。例如:

  • /artists/2
    ArtistsIndexController
    查看
    /www/artists/index.html
  • /artists/name
    ArtistsProfileController
    查看
    /www/artists/profile.html
理想情况下,我会使用以下内容:

$routeProvider.when("/artists/:page", {
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$routeProvider.when("/artists/:name", {
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});
其中,
:page
是一个数字,
:name
不是


注意:我看到一个相关的(从中找到),但我想知道是否有解决方案或首选解决方案。

我现在将此作为一个解决方案,并对替代方案感兴趣

1) 创建将在控制器中加载并动态查看的通用模板:

<div ng-controller="controller" ng-include src="templateUrl"></div>
3) 无论参数类型如何,均使用一条管线:

// handles both /artists/2 and /artists/username
$routeProvider.when("/artists/:pageOrName", {
  templateUrl: "/www/shared/dynamic-controller.html",
  controller: "ArtistsDynamicRouteController"
});
另一种方法是使用,它支持路由正则表达式(在一系列其他内容中),这将允许:

$stateProvider.state("artists-index", {
  url: "/artists/{page:[0-9]*}",
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$stateProvider.state("artists-profile", {
  url: "/artists/{name}",
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});

我使用了一个讨厌的黑客,那就是修改regexp

var $route = $routeProvider.$get[$routeProvider.$get.length-1]({$on:function(){}});


$routeProvider.when("/artists/:page", {
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$routeProvider.when("/artists/:name", {
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});

$route.routes['/artist/:page'].regexp = /^\/(?:artist\/(\d+))$/
$route.routes['/artist/:page/'].regexp = /^\/(?:artist\/(\d+))\/$/
它很难看,但很好用。
您可以更改路由的regexp,使其与您想要的匹配

请参阅,以了解在执行此操作时有关缩小的问题。非常感谢,这对我非常有帮助:)路由和状态之间有什么区别?@Apul当我使用ui路由器时,每个状态都有一条路由,所以我只将状态视为一条路由。提到不是每个州都需要一条路线,但一开始我并不担心。您还可以查看有关泛型状态机概念的更多详细信息。
var $route = $routeProvider.$get[$routeProvider.$get.length-1]({$on:function(){}});


$routeProvider.when("/artists/:page", {
  templateUrl: "/www/artists/index.html",
  controller: "ArtistsIndexController"
});

$routeProvider.when("/artists/:name", {
  templateUrl: "/www/artists/profile.html",
  controller: "ArtistsProfileController"
});

$route.routes['/artist/:page'].regexp = /^\/(?:artist\/(\d+))$/
$route.routes['/artist/:page/'].regexp = /^\/(?:artist\/(\d+))\/$/