我一直在尝试使用以下方法将一些项目添加到可滚动容器内的列表中ng-repeat
,最近的应该位于列表的顶部。如果在添加内容时容器的滚动条不在最顶部,我还需要保持滚动位置。
这是我的解决方案,但我仍然有问题。 Angular 在 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;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body ng-app="myApp">
<div class="stream-container" ng-controller="MainCtrl">
<div class="stream">
<div class="item" ng-repeat="item in items track by item.id">{{ item.text }}</div>
</div>
</div>
</body>
I found 这个帖子 http://blogs.microsoft.co.il/choroshin/2014/04/08/angularjs-postdigest-vs-timeout-when-dom-update-is-needed/并改变了$timeout
to $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;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body ng-app="myApp">
<div class="stream-container" ng-controller="MainCtrl">
<div class="stream">
<div class="item" ng-repeat="item in items track by item.id">{{ item.text }}</div>
</div>
</div>
</body>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)