Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  3] [ 6]  / answers: 1 / hits: 72417  / 10 Years ago, wed, june 4, 2014, 12:00:00

I am using AngularJS for a small web app and have encountered a problem. I am using ng-repeat to populate a list inside of a div. The div has a fixed height and is set to overflow-y: auto, meaning a scroll bar appears when the list is too big for the div. My problem is that when the list gets re-drawn, i.e. the data backing ng-repeat changes, the scroll bar does not reset to the top of the div. Instead, it stays at whatever position the scroll bar was at before the ng-repeat change. This is a very poor user experience. I've tried the following without any luck:



<div id=myList>
<ul>
<li ng-repeat=item in items>{{item}}</li>
</ul>
</div>

<a ng-click=switchItems()>Switch</a>

<script>
function MyApp($scope) {
$scope.switchItems = function() {
$('#myList').scrollTop();
$scope.items = [1, 2, 3, 4]; // new items
};
}
</script>

More From » jquery

 Answers
24

I've had the same issue and I usually solve it with the following generic directive. It listens to a given event and whenever that event happens, it scrolls the element back to y = 0. All you need to do is $broadcast the event in your controller when your list changes.



angular.module(ui.scrollToTopWhen, [])
.directive(scrollToTopWhen, function ($timeout) {
function link (scope, element, attrs) {
scope.$on(attrs.scrollToTopWhen, function () {
$timeout(function () {
angular.element(element)[0].scrollTop = 0;
});
});
}
});


Usage:



// Controller
$scope.items = [...];
$scope.$broadcast(items_changed)

// Template
<div id=myList scroll-to-top-when=items_changed>

[#70728] Tuesday, June 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiyam

Total Points: 448
Total Questions: 96
Total Answers: 92

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;