39

我有一个简单的项目清单。每当我添加更多项目时,我希望能够滚动到显示项目的元素底部。我知道没有办法挂钩到$apply()函数的末尾,那么我的解决方案可能是什么?

这是一个jsfiddle来说明我的问题。添加足够的项目后, ul 元素不会滚动到底部...

4

6 回答 6

70

有非常棒的angularjs-scroll-glue可用,它完全符合您的要求。

您需要做的就是将该scroll-glue指令应用于您的容器元素,然后您就会得到您正在寻找的东西。

还有一个可用的演示

于 2014-03-14T14:01:35.587 回答
29

另一个有效的解决方案是使用$timeout. 使用 0 的超时值,angular 将等到 DOM 被渲染后再调用你传递给的函数$timeout。因此,在将元素添加到列表后,您可以使用它来等待新元素添加到 DOM 中,然后再滚动到底部。

就像@Mark Coleman解决方案一样,这不需要任何额外的外部库。

var myApp = angular.module('myApp', []);

function MyCtrl($scope, $timeout) {
  $scope.list = ["item 1", "item 2", "item 3", "item 4", "item 5"];
  $scope.add = function() {
    $scope.list.push("new item");
    $timeout(function() {
      var scroller = document.getElementById("autoscroll");
      scroller.scrollTop = scroller.scrollHeight;
    }, 0, false);
  }
}
ul {
  height: 150px;
  overflow: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <button ng-click="add()">Add</button>
    <ul id="autoscroll">
      <li ng-repeat="item in list">{{item}}</li>
    </ul>
  </div>
</div>

于 2015-10-08T15:04:13.223 回答
9

一个简单的工作示例(不需要插件或指令)...

.controller('Controller', function($scope, $anchorScroll, $location, $timeout) {

  $scope.func = function(data) {

    // some data appending here...

    $timeout(function() {
      $location.hash('end');
      $anchorScroll();
    })
  }

})

为我做这件事的技巧是用 包裹 anchorScroll 命令$timeout,这样范围就被解决了,它会自动转移到页面末尾的一个元素。

于 2016-01-16T10:02:58.453 回答
6

您可以创建一个简单的指令来绑定<ul>每次滚动到底部的点击处理程序。

myApp.directive("scrollBottom", function(){
    return {
        link: function(scope, element, attr){
            var $id= $("#" + attr.scrollBottom);
            $(element).on("click", function(){
                $id.scrollTop($id[0].scrollHeight);
            });
        }
    }
});

jsfiddle 上的示例

于 2013-06-25T12:16:02.420 回答
2

您可以使用 AnchorScroll .. 这里的文档:https ://docs.angularjs.org/api/ng/service/$anchorScroll

于 2014-06-26T17:09:32.777 回答
-1

您可以使用 angularjs 自定义目录来实现这一点。

例子 :

<ul style="overflow: auto; max-height: 160px;" id="promptAnswerBlock">

<li ng-repeat="obj in objectKist track by $index" on-finish-render="ngRepeatFinished">                                              

  app.directive('onFinishRender', function($timeout) {
    return {
        restrict : 'A',
        link : function(scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function() {
                    $('#promptAnswerBlock').scrollTop($('#promptAnswerBlock')[0].scrollHeight + 150);
                });
            }
          }
        }
    }); 

</li>
于 2016-08-05T07:23:25.093 回答