【问题标题】:ui-router-- having a route's URL share the same level as another state with $stateParams?ui-router-- 让一个路由的 URL 与另一个状态共享同一级别的 $stateParams?
【发布时间】:2014-11-08 13:48:39
【问题描述】:

我想在我的应用程序中执行类似的操作,其中同一级别的 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-router总是达到biz 状态,并将“baz”解释为该状态的参数。有没有一种优雅的方式让 ui-router 知道任何点击“/baz”的东西都应该解析为baz 状态?

我知道我可以使用 $stateChangeStart 并执行以下操作:

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

但这远非优雅,而且看起来像是一个 hack。

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    我创建了a plunker here,这实际上表明上述状态 sn-p 正在工作。为什么,因为这些状态是按正确的顺序定义的:

    .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...
        ...
    })
    

    查看broken link here

    总结:

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

    【讨论】:

    • 这真的很奇怪。它肯定在您创建的 plunker 中工作,但在我的应用程序中不起作用。感谢您抽出时间对此进行调查,我将不得不隔离更多情况并弄清楚到底发生了什么。
    • 想通了。 这是因为我试图达到的第一个状态是抽象的,而且无论顺序如何,它看起来都像角度服从非抽象状态。
    • 太棒了,你成功了!享受 ui-router :)
    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多