在角度ui-router中更改状态而不更改浏览器历史记录

时间:2022-03-04 11:23:46

Assume that we have a logic like this:

假设我们有这样的逻辑:

  • From state A, change to state B.
  • 从状态A,切换到状态B.
  • Whenever we arrive to state B, the app always redirect us to state C by calling $state.go(stateC)
  • 每当我们到达状态B时,应用程序总是通过调用$ state.go(stateC)将我们重定向到状态C.
  • Now we are in state C
  • 现在我们处于C州

My question is how to go back to state A from state C (given the fact that state A can be any state we don't know at run-time, meaning user can access state B from any other states)

我的问题是如何从状态C回到状态A(假设状态A可以是我们在运行时不知道的任何状态,这意味着用户可以从任何其他状态访问状态B)

2 个解决方案

#1


26  

Use the location option with value "replace"...

使用值为“replace”的location选项...

$state.go(stateC, null, {
    location: 'replace'
})

See https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_go

请参阅https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_go

location - {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record.

location - {boolean = true | string =} - 如果为true,则更新位置栏中的url,否则为false。如果是string,则必须为“replace”,这将更新url并替换上一个历史记录。

#2


-1  

You could keep track of visited states in a service and then just call $state.go on the previous state.

您可以跟踪服务中的访问状态,然后在之前的状态下调用$ state.go。

You can watch the state changes like so:

您可以像这样观察状态变化:

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 
    // add fromState to history 
});

How to $watch state change of $stateProvider in AngularJS?

如何在AngularJS中观察$ stateProvider的状态变化?

#1


26  

Use the location option with value "replace"...

使用值为“replace”的location选项...

$state.go(stateC, null, {
    location: 'replace'
})

See https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_go

请参阅https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_go

location - {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record.

location - {boolean = true | string =} - 如果为true,则更新位置栏中的url,否则为false。如果是string,则必须为“replace”,这将更新url并替换上一个历史记录。

#2


-1  

You could keep track of visited states in a service and then just call $state.go on the previous state.

您可以跟踪服务中的访问状态,然后在之前的状态下调用$ state.go。

You can watch the state changes like so:

您可以像这样观察状态变化:

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 
    // add fromState to history 
});

How to $watch state change of $stateProvider in AngularJS?

如何在AngularJS中观察$ stateProvider的状态变化?