Scroll to bottom in chat box in angularjs

前端 未结 2 1844
Happy的楠姐
Happy的楠姐 2020-12-30 21:07

I am trying to automatically scroll to bottom whenever there is a new message.

My code moves the scrollbar but it does not take it to exact bottom. Kindly help. Her

相关标签:
2条回答
  • 2020-12-30 21:23

    Thanks @MajoB

    Here are my 2 cents including:

    • removed jQuery dependency
    • added a $timeout to make sure $digest cycle is finished

    ngScrollBottom.js:

    angular.module('myApp').directive('ngScrollBottom', ['$timeout', function ($timeout) {
      return {
        scope: {
          ngScrollBottom: "="
        },
        link: function ($scope, $element) {
          $scope.$watchCollection('ngScrollBottom', function (newValue) {
            if (newValue) {
              $timeout(function(){
                $element.scrollTop($element[0].scrollHeight);
              }, 0);
            }
          });
        }
      }
    }]);
    
    0 讨论(0)
  • 2020-12-30 21:24

    You can create a directive for this:

    .directive('scrollBottom', function () {
      return {
        scope: {
          scrollBottom: "="
        },
        link: function (scope, element) {
          scope.$watchCollection('scrollBottom', function (newValue) {
            if (newValue)
            {
              $(element).scrollTop($(element)[0].scrollHeight);
            }
          });
        }
      }
    })
    

    http://plnkr.co/edit/H6tFjw1590jHT28Uihcx?p=preview

    BTW: avoid DOM manipulation inside controllers (use directives instead).

    0 讨论(0)
提交回复
热议问题