我正在创建一个显示一些数据的基于选项卡的页面。 我在 AngularJs 中使用 UI-Router 来注册状态。
我的目标是在页面加载时打开一个默认选项卡。每个选项卡都有子选项卡,我希望在更改选项卡时打开默认子选项卡。
我正在使用 onEnter
函数进行测试,在内部我正在使用 $state.go('mainstate.substate');
但由于循环,它似乎无法工作效果问题(在 state.go to substate 上它调用它的父状态等等,然后它变成了一个循环)。
$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 .
现在一切正常,除了我没有打开默认选项卡,而这正是我需要的。
感谢您的建议、意见和想法。
最佳答案
更新: 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 评论的选项以保留浏览器历史记录。
关于javascript - 在 AngularJS 中使用 UI-Router 将状态重定向到默认子状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29491079/