我想切换两个div(屏幕)并在切换时返回相同的滚动位置。问题是在滚动窗口时仍然呈现旧版本(滚动的错误时间)。因此,如果div'A'最大滚动位置为200且div B max scroll为100,那么我可以回归到'A'的最大位置是100
<body ng-controller="MainCtrl">
<div ng-show='showToggle'>
Screen A
<ul>
<li ng-repeat="a in getArray(200) track by $index">
<a href="" ng-click="show()">
a:{{$index}}
</a>
</li>
</ul>
</div>
<div ng-show='!showToggle'>
Screen B
<ul>
<li ng-repeat="b in getArray(100) track by $index">
<a href="" ng-click="show()">
b:{{$index}}
</a>
</li>
</ul>
</div>
</body>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $window) {
$scope.showToggle = true;
$scope.getArray=function(size){
return new Array(size);
}
$scope.scrollState = {};
$scope.show = function(){
//Saves current window position of scroll for the future
$scope.scrollState[$scope.showToggle] = $window.pageYOffset;
//Activates different div with different scroll length
$scope.showToggle = !$scope.showToggle;
//At this time window scroll length is still showing for previous div
$window.scrollTo(0, $scope.scrollState[$scope.showToggle]);
}
});
建议的解决方案是什么?基本上我只是想知道什么时候窗口的'大小'是准确的(适当的div渲染/隐藏)是最早的点,我怎么能以角度来听这个事件。
答案 0 :(得分:1)
使用$timeout
让角度完成其脏检查工作并更新DOM然后滚动窗口。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $window, $timeout) {
$scope.showToggle = true;
$scope.getArray=function(size){
return new Array(size);
}
$scope.scrollState = {};
$scope.show = function(){
//Saves current window position of scroll for the future
$scope.scrollState[$scope.showToggle] = $window.pageYOffset;
//Activates different div with different scroll length
$scope.showToggle = !$scope.showToggle;
$timeout(function(){
//At this time window scroll length is still showing for previous div
$window.scrollTo(0, $scope.scrollState[$scope.showToggle]);
});
}
});