ui-router--让路由的 URL 与 $stateParams 的另一个状态共享相同的级别? [英] ui-router-- having a route's URL share the same level as another state with $stateParams?

查看:20
本文介绍了ui-router--让路由的 URL 与 $stateParams 的另一个状态共享相同的级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中做这样的事情,其中​​相同级别的 URL 命中 baz 状态,绝对命名,或 biz 带有参数的状态.

I'd like to do something like this in my application, where the same level of the URL hits the either the baz state, that absolutely named, or the biz state that takes a parameter.

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 状态?

However, what's happening is ui-router is always hitting the biz state, and interpreting "baz" as a parameter for that state. Is there an elegant way to let ui-router know that anything that hits "/baz" should resolve to the baz state?

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

I know I can use $stateChangeStart and do something like this:

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

但这远非优雅,而且似乎是一种黑客行为.

But this is far from elegant and seems like a hack.

推荐答案

我在这里创建了一个plunker,这实际上表明,上面的 state 片段是有效的.为什么,因为这些状态是以正确的顺序定义的:

I created a plunker here, which in fact shows, that the above state snippet is WORKING. Why, because these states are defined in the correct order:

.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:

The way how we can make it broken, is to switch the state def:

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

检查此处的断开链接

总结:

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

state definition order is important. The first state url match is used

这篇关于ui-router--让路由的 URL 与 $stateParams 的另一个状态共享相同的级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆