Conserver la position de défilement lors de l’ajout de contenu à une liste (AngularJS)

J’ai essayé d’append certains éléments à une liste dans un conteneur avec fonction de défilement à l’aide de ng-repeat , le fichier récent devant figurer en haut de la liste. Je dois également conserver la position de défilement si la barre de défilement du conteneur n’est pas tout à fait en haut lors de la présélection de contenu.

Voici ma solution, mais j’ai toujours un problème. Il y a toujours un scintillement après que angular a rendu les éléments ajoutés au début.

 var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', function($scope, $interval, $timeout) { $scope.items = []; $interval(function() { var item = { id: Math.random(), text: (new Date()).toSsortingng() }; $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 }}

J’ai trouvé ce post et changé $timeout en $scope.$$postDigest . Maintenant, cela fonctionne comme prévu.

 var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', function($scope, $interval, $timeout) { $scope.items = []; $interval(function() { var item = { id: Math.random(), text: (new Date()).toSsortingng() }; $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 }}