Scroll to top of div in AngularJS?

前端 未结 4 836
情深已故
情深已故 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:31

    I would simply add a directive that watches the content of the DIV. It would then scroll to the top whenever the content changes! This solution does not require event processing (which I believe is unnecessary here).

    mod.directive('scrollToTop', function(){
        return {
            restrict: 'A',
            link: function postLink(scope, elem, attrs) {
                scope.$watch(attrs.scrollToTop, function() {
                    elem[0].scrollTop = 0;
                });
            }
        };
    });
    

    The html markup would then use the directive to trigger the scrolling thus:

    • {{item}}

    As you add items to the list, the DIV will scroll to the top! Here is a jsFiddle with working code: http://jsfiddle.net/pkgbtw59/89/

提交回复
热议问题