AngularJS正则表达式路由为类似的URL加载不同的控制器和视图

Glo*_*opy 9 javascript routes angularjs

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

  • /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"
});
Run Code Online (Sandbox Code Playgroud)

数字在哪里:page:name不是.

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

Glo*_*opy 5

另一种方法是使用ui-router,它支持路由的正则表达式(在一系列其他东西中),这将允许:

$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"
});
Run Code Online (Sandbox Code Playgroud)


Glo*_*opy 1

我现在使用这个作为解决方案,并且对替代方案感兴趣!

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

<div ng-controller="controller" ng-include src="templateUrl"></div>
Run Code Online (Sandbox Code Playgroud)

在此示例中,我将此视图放置在/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';
    }
  }]);
Run Code Online (Sandbox Code Playgroud)

3) 无论参数类型如何,都使用一个路由:

// handles both /artists/2 and /artists/username
$routeProvider.when("/artists/:pageOrName", {
  templateUrl: "/www/shared/dynamic-controller.html",
  controller: "ArtistsDynamicRouteController"
});
Run Code Online (Sandbox Code Playgroud)