如何通过在不重新加载页面的情况下更改$ stateParams来更改URL

ltf*_*hie 9 angularjs angular-ui-router

我有一个定义参数的路由:

$stateProvider
.state('item', {..})
.state('item.view', {
  url: 'item/:id'
  template: '...',
  controller: '...'
});
Run Code Online (Sandbox Code Playgroud)

虽然已经处于item.view状态,但我想切换网址

$state.go('item.view', {id: 'someId'})
Run Code Online (Sandbox Code Playgroud)

无需重新加载页面.我试过了:

$state.go('item.view', {id: 'someId'}, {notify: false});
$state.go('item.view', {id: 'someId'}, {notify: false, reload: false});
Run Code Online (Sandbox Code Playgroud)

两者仍然导致页面重新加载.我想我可能会遇到这里描述的问题:https://github.com/angular-ui/ui-router/issues/1758

Dju*_*uka 4

这应该很容易:

// It needs to be executed on main scope, hence $timeout
// If you are calling from a controller this is a must
// Otherwise it will 'lag' and update on next function call
$timeout(function() {
    // As Sheryar Abbasi commented, the rest is simple.
    // You should call $state.transitionTo with notify: false
    // to stop the reload.
    $state.transitionTo(
        'item.view', 
        { 
            id: 4378 // New id/$stateParams go here 
        }, 
        { 
            location: true, // This makes it update URL
            inherit: true, 
            relative: $state.$current, 
            notify: false // This makes it not reload
        }
    ); 
});
Run Code Online (Sandbox Code Playgroud)

这个 StackOverflow 线程帮助我找出了 $timeout。

是官方 ui-router 快速参考。