我有一个项目,我将 angularJS 与 ui.router 一起使用,并且我们有一个事件列表,如果用户单击事件以查看详细信息,则该列表可能会很长(具有无限滚动),但是在单击返回时会显示后退按钮div 的滚动重置回到顶部!寻找一些关于是否有任何内置内容可以用来记住此滚动位置的建议,我知道有 anchorscroll 服务,但我想知道是否有更适合阻止 angular 在导航中重置滚动位置的内容??因为有一些类似的列表需要在滚动时记住它们的状态。
示例在 http://codedef.com/hapzis_poc/ .不是完整的证明,但应该能够向下滚动事件,单击左右并返回并保持相同的滚动位置..
最佳答案
有一个关于类似主题的对话( ng-view
),@br2000 给出的答案对我有用。
https://stackoverflow.com/a/25073496/3959662
使他的指令适用于 ui-router
请执行下列操作:
1. 像这样创建新指令:
(function () {
'use strict';
angular
.module('your.module.directives')
.directive('keepScrollPos', keepScrollPos);
function keepScrollPos($route, $window, $timeout, $location, $anchorScroll, $state) {
// cache scroll position of each route's templateUrl
var scrollPosCache = {};
// compile function
var directive = function (scope, element, attrs) {
scope.$on('$stateChangeStart', function () {
// store scroll position for the current view
if($state.$current)
{
scrollPosCache[$state.current.templateUrl] = [$window.pageXOffset, $window.pageYOffset];
}
});
scope.$on('$stateChangeSuccess', function () {
// if hash is specified explicitly, it trumps previously stored scroll position
if ($location.hash()) {
$anchorScroll();
// else get previous scroll position; if none, scroll to the top of the page
} else {
var prevScrollPos = scrollPosCache[$state.current.templateUrl] || [0, 0];
$timeout(function () {
$window.scrollTo(prevScrollPos[0], prevScrollPos[1]);
}, 0);
}
});
};
return directive;
}
})();
2. 在您拥有
ui-view
的元素上使用它属性,就我而言:<div class="col-xs-12" ui-view keep-scroll-pos></div>
关于angularjs - 如何使用/Ui.ROUTER在angularJS中 'remember'滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828219/