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

时间:2015-05-17 02:36:18

标签: angularjs angular-ui-router

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

$stateProvider
.state('item', {..})
.state('item.view', {
  url: 'item/:id'
  template: '...',
  controller: '...'
});

当已经处于 item.view 状态时,我想用

切换网址
$state.go('item.view', {id: 'someId'})

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

$state.go('item.view', {id: 'someId'}, {notify: false});
$state.go('item.view', {id: 'someId'}, {notify: false, reload: false});

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

1 个答案:

答案 0 :(得分:2)

这应该很容易:

// 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
        }
    ); 
});

This StackOverflow thread帮助我找出$ timeout。

Here是官方的ui-router快速参考。