【发布时间】:2016-05-17 21:46:14
【问题描述】:
在我的单页应用程序中,我需要保留状态历史记录,以便更轻松地在状态之间来回导航。我有自己的前进和后退按钮,我在我的页面上使用,而不是通过浏览器的按钮。
这是我拥有的以下代码,它使用我创建的服务将状态存储在数组中。
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
StateMgmtService.add(toState, toParams);
});
在服务中,我有一些大意如下:
var history = [];
return {
previous: function () {
if (history && history.length > 0) {
return history[history.length - 1];
}
},
add: function (state, params) {
var historyItem = {
state: state,
parameters: params
};
history.push(historyItem);
}
};
问题是,每当我回到之前的状态时,stateChangeStart 都会被触发,这基本上会污染我的历史记录。考虑以下示例:
- 从状态 a 开始到 b - b 被添加到历史记录中
- b 到 c - c 被添加
- c 返回 b - b 再次添加
这导致从 b 到 c 到 b 到 c 的无限循环......所以我基本上不需要允许将先前的项目添加到历史记录中,或者以某种方式知道它会回到历史记录中,但是stateChangeStart 不允许任何区分。
救命!
【问题讨论】:
标签: javascript angularjs angular-ui-router single-page-application