Scroll to top of div in AngularJS?

前端 未结 4 826
情深已故
情深已故 2021-02-03 18:39

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

4条回答
  •  隐瞒了意图╮
    2021-02-03 19:18

    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
    

提交回复
热议问题