将内容添加到列表时保持滚动位置(AngularJS)
我一直试图通过使用ng-repeat
将一些项目添加到可滚动容器中的列表中,并且最近的一个应该位于列表的顶部。 如果在添加内容时容器的滚动条不在顶部,我还需要保持滚动位置。
这是我的解决方案,但我仍有问题。 在角度为dom渲染前置项目后,总会出现闪烁。
var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', function($scope, $interval, $timeout) { $scope.items = []; $interval(function() { var item = { id: Math.random(), text: (new Date()).toString() }; $scope.items.unshift.apply($scope.items, [item]); var $container = $('.stream-container'); var $topItem = $('.item:first'); var oScrollTop = $container.scrollTop(); var oOffset = $topItem.length ? $topItem.position().top : 0; $timeout(function() { // Executed after the dom has finished rendering if ($container.scrollTop() !== 0) { $container.scrollTop(oScrollTop + ($topItem.length ? $topItem.position().top : 0) - oOffset); } }); }, 1000); });
.stream-container { overflow-y: scroll; overflow-x: none; height: 100px; position: relative; }
{{ item.text }}
我发现这篇文章并将$timeout
更改$timeout
$scope.$$postDigest
。 现在它按预期工作。
var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', function($scope, $interval, $timeout) { $scope.items = []; $interval(function() { var item = { id: Math.random(), text: (new Date()).toString() }; $scope.items.unshift.apply($scope.items, [item]); var $container = $('.stream-container'); var $topItem = $('.item:first'); var oScrollTop = $container.scrollTop(); var oOffset = $topItem.length ? $topItem.position().top : 0; $scope.$$postDigest(function() { // Executed after the dom has finished rendering if ($container.scrollTop() !== 0) { $container.scrollTop(oScrollTop + ($topItem.length ? $topItem.position().top : 0) - oOffset); } }); }, 1000); });
.stream-container { overflow-y: scroll; overflow-x: none; height: 100px; position: relative; }
{{ item.text }}