使用 AngularJS 中的 UI-Router 将状态重定向到默认子状态 [英] Redirect a state to default substate with UI-Router in AngularJS

查看:23
本文介绍了使用 AngularJS 中的 UI-Router 将状态重定向到默认子状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个基于选项卡的页面,其中显示了一些数据.我在 AngularJs 中使用 UI-Router 来注册状态.

I'm creating a tab based page which shows some data. I'm using UI-Router in AngularJs to register states.

我的目标是在页面加载时打开一个默认选项卡.每个选项卡都有子选项卡,我希望在更改选项卡时打开一个默认的子选项卡.

My aim is to have one default tab open on page load. Each tab have sub tabs, and I would like to have a default sub tab open when changing tabs.

我正在使用 onEnter 函数进行测试,在内部我使用的是 $state.go('mainstate.substate'); 但由于循环,它似乎不起作用效果问题(在 state.go 上调用其父状态等子状态,然后变成一个循环).

I was testing with onEnter function and inside I'm using $state.go('mainstate.substate'); but it seems not to work due to loop effect issues (on state.go to substate it calls its parent state and so on, and it turns into a loop).

$stateProvider

.state('main', {
  url: '/main',
  templateUrl: 'main.html',
  onEnter: function($state) {
    $state.go('main.street');
  }
})

.state('main.street', {
  url: '/street',
  templateUrl: 'submenu.html',
  params: {tabName: 'street'}
})

在这里我创建了一个 plunker 演示.

Here I created a plunker demo.

现在一切正常,只是我没有打开默认选项卡,这正是我需要的.

For now everything works, except that I don't have the default tab open and that's exactly what I need.

感谢您的建议、意见和想法.

Thank you for your suggestions, opinions and ideas.

推荐答案

更新:1.0 以后支持redirectTo 开箱即用.

Update: 1.0 Onwards Supports redirectTo out of the box.

https://ui-router.github.io/ng1/docs/latest/interfaces/state.statedeclaration.html#redirectto

我在此处创建了示例.

此解决方案来自对使用 .when() 重定向问题的一个不错的评论"(https://stackoverflow.com/a/27131114/1679310)非常酷的解决方案(由 Chris T 撰写,但原帖由 yahyaKacem 撰写)

This solution comes from a nice "Comment" to an an issue with redirection using .when() (https://stackoverflow.com/a/27131114/1679310) and really cool solution for it (by Chris T, but the original post was by yahyaKacem)

https://github.com/angular-ui/ui-router/issues/1584#issuecomment-75137373

所以首先让我们使用重定向设置扩展 main:

So firstly let's extend main with redirection setting:

$stateProvider
    .state('main', {
      url: '/main',
      templateUrl: 'main.html',
      redirectTo: 'main.street',
    })

在运行中只添加这几行

app.run(['$rootScope', '$state', function($rootScope, $state) {

    $rootScope.$on('$stateChangeStart', function(evt, to, params) {
      if (to.redirectTo) {
        evt.preventDefault();
        $state.go(to.redirectTo, params, {location: 'replace'})
      }
    });
}]);

通过这种方式,我们可以使用默认重定向来调整我们的任何状态...检查它这里

This way we can adjust any of our states with its default redirection...Check it here

从@Alec 的评论中添加选项以保留浏览器历史记录.

Added option from comment by @Alec to preserve the browser history.

这篇关于使用 AngularJS 中的 UI-Router 将状态重定向到默认子状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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