接受指定状态URL后的任何后续字符

问题描述

我正在使用ui-router,并且我的一个状态URL可以附加动态键。所以状态看起来像这样:

.state('reset-password',{
    url: '/reset-password/{.*}',template: require('html-loader!./features/forgot-password/html/reset-password.tpl.htm'),controller: 'ResetPasswordController',controllerAs: '$ctrl',}) 

但是URL可能是/reset-password/13404[email protected]

但是,如果输入了该状态,将不会识别该状态,并且认情况下会通过加载/login状态:

$urlRouterProvider 
    .otherwise("/login")

问题

/reset-password之后,如何允许任何后续的动态URL?

解决方法

如果您希望URL的尾部匹配状态,则可以使用以下(等效)语法之一:

  • /reset-password/{path:.*}
  • /reset-password/*path

要注意的共同点是结尾部分绑定到名称(即path)。

然后,您应该可以通过控制器中的$stateParams进行访问。

或者,如果您想让ui-router做更多解析URL参数的繁重工作,您也可以这样做。

包括以下一些方法:

angular
  .module('app',['ui.router'])
  .config(function ($stateProvider) {
    $stateProvider
      .state({
        name: 'reset-password1',url: '/reset-password1/*path',controller: function ($stateParams) {
          this.path = $stateParams.path;
        },controllerAs: '$ctrl',template: '<pre>path={{$ctrl.path}}</pre>'
      })
      .state({
        name: 'reset-password2',url: '/reset-password2/:id?email',controller: function ($stateParams) {
          this.id = $stateParams.id;
          this.email = $stateParams.email;
        },template: '<pre>id={{$ctrl.id}} email={{$ctrl.email}}</pre>'
      });
  });
<div ng-app="app">
  <a ui-sref="reset-password1({ path: '[email protected]' })" ui-sref-active="active">Reset Password (1)</a>
  <a ui-sref="reset-password2({ id: 134042,email: '[email protected]' })" ui-sref-active="active">Reset Password (2)</a>
  <ui-view></ui-view>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.28/angular-ui-router.min.js "></script>