AngularJS:应用DOM更改后滚动到元素结尾

时间:2013-06-25 12:03:35

标签: angularjs

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

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

6 个答案:

答案 0 :(得分:69)

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

您需要做的就是将scroll-glue指令应用于容器元素,并且您可以得到您正在寻找的内容。

还有demo可用。

答案 1 :(得分:28)

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

@Mark Colemansolution一样,这不需要任何额外的外部库。

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>

答案 2 :(得分:7)

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

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

  $scope.func = function(data) {

    // some data appending here...

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

})

为我做的诀窍是使用$timeout包装anchorScroll命令,这样就解决了范围并自动转移到页面末尾的元素。

答案 3 :(得分: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);
            });
        }
    }
});

<强> example on jsfiddle

答案 4 :(得分:2)

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

答案 5 :(得分:-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>
相关问题