AngularJS: Scroll to end of element after applying DOM changes

前端 未结 6 969
攒了一身酷
攒了一身酷 2020-12-29 20:16

I have a simple list of items. I want to be able to scroll to the bottom of the element displaying the items whenever I add more items. I understood there is no way of hooki

6条回答
  •  忘掉有多难
    2020-12-29 21:02

    Another valid solution to this is using $timeout. Using a timeout value of 0, angular will wait until the DOM is rendered before calling the function you pass to $timeout. So, after you add an element to the list, you can use this to wait for your new element to be added to the DOM before scrolling to the bottom.

    Like @Mark Coleman's solution, this won't require any extra external libraries.

    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;
    }
    
    
    • {{item}}

提交回复
热议问题