changing scroll top inside angular directive doesn't work

In my directive I wrote my logic for dynamic pagination (lazy loading), each time the user scroll to the bottom of the page I append more elements to it , this works fine but I want to to change the scroll position after that but it doesn't work.
This is my code :

 link: function(scope, element) {

            var usersArea = $(".usersArea");

            usersArea.bind("scroll", function() {

                var scrollHeight = $(this)[0].scrollHeight;
                var scrollTop = $(this)[0].scrollTop;
                var clientHeight = $(this)[0].clientHeight;
                var downloadMore = scrollHeight - scrollTop - clientHeight < 50;

                if (downloadMore) {
                    var childScope = scope.$new();    

                    usersContainer = scope.displayPortion(usersContainer);
                    if (usersContainer) {
                        $compile(usersContainer)(childScope);
                        //This doesn't work !!
                        $(this)[0].scrollTop = 500;
                    }
                }
            });    
}

I tried to change the scroll position using native javascript and with JQuery but nothings seem to work, any suggestions ?

Answers 1

  • Since the compile is not immediate procedure I would suggest to postpone any operations with the result of compiling. The easiest (but not the best) way is to use simple timer:

      var elt = $(this)[0];
      var scrollHeight = elt.scrollHeight;
      var scrollTop = elt.scrollTop;
      var clientHeight = elt.clientHeight;
      var downloadMore = scrollHeight - scrollTop - clientHeight < 50;
    
      if (downloadMore) {
          var childScope = scope.$new();    
          usersContainer = scope.displayPortion(usersContainer);
          if (usersContainer) {
              $compile(usersContainer)(childScope);
              setTimeout(function() {
                elt.scrollTop = 500;
              });
          }
      } 
    

Related Articles