ui路由器——具有一条路由'的URL与另一个具有$stateParams的状态共享同一级别

ui-router-- having a route's URL share the same level as another state with $stateParams?

本文关键字:stateParams 状态 共享 一级 URL 路由 一条路 一条 路由器 ui 另一个      更新时间:2023-09-26

我想在我的应用程序中做这样的事情,其中相同级别的URL要么是绝对命名的baz状态,要么是接受参数的biz状态。

angular.module('foo')
.config(function($stateProvider){
  $stateProvider
  .state('baz', {
    url: '/baz',
    templateUrl: '/templates/baz.html'
  })
  .state('biz', {
    url: '/:biz',
    templateUrl: '/templates/biz.html',
    resolve: {
      biz: function($stateParams){
        // resolve whatever $stateParams.biz should be
      }
    }
  })
})

然而,现在发生的情况是ui路由器总是进入biz状态,并将"baz"解释为该状态的参数。有没有一种优雅的方法可以让ui路由器知道,任何命中"/baz"的东西都应该解析为baz状态?

我知道我可以使用$stateChangeStart做一些类似的事情:

$rootScope.$on('$stateChangeStart', function(event, toState, toParams){
  if (toParams.biz === "baz"){
    event.preventDefault();
    $state.go('baz')
  }
})

但这一点都不优雅,看起来像是一个黑客。

我在这里创建了一个plunker,它实际上表明,上面的状态片段正在工作。为什么,因为这些状态是按照正确的顺序定义的:

.state('baz', {
    url: '/baz', // url '/baz' is registered first, will be find and used
    ...
})
.state('biz', {
    url: '/:biz', // '/baz' will never reach this, because is already handled
    ...

我们如何让它坏掉,就是切换状态def:

.state('biz', {
    url: '/:biz', // '/baz' will be handled by this state
    ...
.state('baz', {
    url: '/baz', // url '/baz' never reach this state def...
    ...
})

检查此处的断开链接

摘要:

状态定义顺序很重要使用第一个状态url匹配