在AngularJS中滚动到div的顶部? [英] Scroll to top of div in AngularJS?

查看:1015
本文介绍了在AngularJS中滚动到div的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularJS的小型网络应用程序,并遇到了一个问题。我使用 ng-repeat 填充div中的列表。 div具有固定的高度,并设置为 overflow-y:auto ,这意味着当列表对于div太大时,会出现滚动条。我的问题是,当列表重新绘制,即数据支持重复更改,滚动条不会重置到div的顶部。相反,它在ng-repeat更改之前停留在滚动条所处的任何位置。这是一个非常糟糕的用户体验。我试过下面没有运气:

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>


推荐答案

我有同样的问题,它与以下通用指令。它监听一个给定的事件,并且每当该事件发生时,它将元素滚动回 y = 0

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;
      });
    });
  }
});

用法:

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

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

这篇关于在AngularJS中滚动到div的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆