Angular - 动态选择起始状态 [英] Angular - Dynamically Choose Starting State
问题描述
很明显,我的应用程序会自动以默认状态启动(即 url:/").我们称之为状态A
.
My app automatically starts at the default state (that has url: "/"), obviously. Let's call it state A
.
如果某个条件为真,我想保留它.这意味着如果 x === 4
例如,那么我希望状态 B
成为第一个加载的状态.
I want to hold back on that in case that a certain condition is truthy. Meaning that if x === 4
for instance then I want state B
to be the first one that loads.
我的问题是,当我检查该条件时,例如在 app.run
中,默认状态已经被加载并呈现在视图中,然后才切换到状态B
.
My problem is that by the time I check for that condition, in the app.run
for instance, the default state is already being loaded and presented in the view, and only then switches to state B
.
有什么办法可以阻止状态加载并在我检查条件后才启动它?
Is there any way I can hold back the state loading and kickstart it only after I check the condition ?
推荐答案
有 一个工作示例
正如评论中所讨论的,我们可以使用 UI-Router 附带的原生内置功能.其中之一是 $urlRouterProvider.deferIntercept(defer)
As discussed in comments we can use the native, built-in features, coming with UI-Router. One of them is $urlRouterProvider.deferIntercept(defer)
禁用(或启用)延迟位置更改拦截.
Disables (or enables) deferring location change interception.
如果您希望自定义同步 URL 的行为(例如,如果您希望延迟转换但保留当前 URL),请在配置时调用此方法.然后,在运行时,在您配置自己的 $locationChangeSuccess
事件处理程序后调用 $urlRouter.listen()
.
If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen()
after you have configured your own $locationChangeSuccess
event handler.
我.step - 停止执行
I. step - STOP execution
所以,我们可以在.config()
阶段定义状态
So, we can define states in .config()
phase
.config(['$stateProvider', '$urlRouterProvider','$locationProvider',
function ($stateProvider, $urlRouterProvider,$locationProvider) {
// States
$stateProvider
...
.state('parent', {
...
})
.state('parent.child', {
...
})
;
...
// here we say STOP
$urlRouterProvider.deferIntercept();
}
])
二.步骤 - 在 .run() 中初始化所需内容 - 重新启用执行
II. step - init what needed in .run() - re-enable execution
这可能是一些简单的 run 示例:
This could be some naive example of run:
.run(['$urlRouter', '$timeout', '$state',
function($urlRouter, $timeout, $state) {
$timeout(function(){
// here we turn all on again...
$urlRouter.sync();
$urlRouter.listen();
// there could be some decision, driven by $http load
// we just use some state as default target
$state.go("parent.child");
}, 1000)
}]);
Se 等待一秒钟,然后我们重新启用所有执行并重定向到parent.childd";...但可以是任何其他的,基于在 .run()
阶段
Se do wait for a second and then we do re-enable all the execution and redirect to "parent.childd" ... but could be any other, based on some decision done in .run()
phase
检查它这里
这篇关于Angular - 动态选择起始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!