使用AngularJS中的UI-Router将状态重定向到默认子状态

问题描述 投票:85回答:6

我正在创建一个基于标签的页面,显示一些数据。我在AngularJs中使用UI-Router来注册状态。

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

我正在使用onEnter函数进行测试,并且我正在使用$state.go('mainstate.substate');,但由于循环效果问题似乎无法工作(在state.go上,它调用它的父状态等等,然后变成循环)。

$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 demo

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

感谢您的建议,意见和想法。

javascript angularjs tabs angular-ui-router
6个回答
164
投票

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

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


我创造了an example here

这个解决方案来自对使用.when()https://stackoverflow.com/a/27131114/1679310)重定向的问题的一个很好的“评论”和非常酷的解决方案(由Chris T,但原始帖子是由yahyaKacem)

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

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

$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'})
      }
    });
}]);

这样我们可以使用默认重定向调整任何状态...检查它here

编辑:添加@Alec评论的选项以保留浏览器历史记录。


21
投票

事实上,即使Radim提出的这个解决方案确实完成了这项工作,我还需要记住每个标签的子标签(状态)。

所以我找到了另一种做同样事情的解决方案,但也记得每个标签子状态。

我所要做的就是安装ui-router-extras并使用deep state redirect功能:

$stateProvider
  .state('main.street', {
     url: '/main/street',
     templateUrl: 'main.html',
     deepStateRedirect: { default: { state: 'main.street.cloud' } },
  });

谢谢!


11
投票

从ui-router的version 1.0开始,它支持redirectTo属性。例如:

.state('A', {
  redirectTo: 'A.B'
})

6
投票

从ui-router 1.0版开始,使用IHookRegistry.onBefore()引入了一个默认钩子,如http://angular-ui.github.io/ui-router/feature-1.0/interfaces/transition.ihookregistry.html#onbefore中的示例数据驱动默认子窗口所示。

// state declaration
{
  name: 'home',
  template: '<div ui-view/>',
  defaultSubstate: 'home.dashboard'
}

var criteria = {
  to: function(state) {
    return state.defaultSubstate != null;
  }
}
$transitions.onBefore(criteria, function($transition$, $state) {
  return $state.target($transition$.to().defaultSubstate);
});

1
投票
app.config(function($stateProvider,$urlRouterProvider){

    $urlRouterProvider.when("/state","/state/sub-state");

    })

1
投票

如果有人来这里寻求关于如何实现状态的简单重定向的答案,并且因为它发生在我身上,没有机会使用新的路由器......

显然,如果可以的话,@ bblackwo的答案很棒:

$stateProvider.state('A', {
  redirectTo: 'B',
});

如果你不能那么只需手动重定向它:

$stateProvider.state('A', {
  controller: $state => {
    $state.go('B');
  },
});

我希望它有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.