在ui-sref链接上保存状态参数

时间:2015-03-11 10:17:40

标签: angular-ui-router ui-sref

情况

有两个子状态使用相同的参数:

$stateProvider
    .state('rootState', {
        url: '/{ID}',
        templateUrl: 'template1.html',
        controller: 'controller1',
        reloadOnSearch: false
    })
    .state('rootState.subStateA', {
        url: '/subStateA',
        parent: 'rootState',
        templateUrl: 'template2.html',
        controller: 'controller2',
        reloadOnSearch: false
    })
    .state('rootState.subStateB', {
        url: '/subStateB/',
        parent: 'rootState',
        templateUrl: 'template3.html',
        controller: 'controller3',
        reloadOnSearch: false
    })

现在,有2个链接:

<a href ui-sref="rootState.subStateA">State A</a>
<a href ui-sref="rootState.subStateB">State B</a>

问题

当我从状态A移动到状态B时,参数ID变为空。

问题

如何在从一种状态移动到另一种状态时保留ID参数?

1 个答案:

答案 0 :(得分:1)

一种方法是将$ stateParams注入$ rootScope并将它们放在任何地方:

.run(['$rootScope', '$state', '$stateParams',
  function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}])

稍后你可以使用这个链接:

<a href ui-sref="rootState.subStateA({ID:$stateParams.ID})">State A</a>
<a href ui-sref="rootState.subStateB({ID:$stateParams.ID})">State B</a>

或者甚至可能

<a href ui-sref="rootState.subStateA($stateParams})">State A</a>
<a href ui-sref="rootState.subStateB($stateParams})">State B</a>