How to get event when user scrolls upwards in angular js?

Could you please tell me how to get the event when the user scrolls up. I mainly use ng-repeat in my example. I want to receive an event when the user scrolls down and scrolls up. I have one div in which I used ng-repeat, we can get an event from the top when the user moves to the start after scrolling. In general, I need to show an alert when the user scrolls down and up a div in angular. Here is my code

<body ng-controller="MyController">
<div style="width:90%;height:150px;border:1px solid red;overflow:auto">
<div ng-repeat="n in name">{{n.name}}</div>
</div>

      

+3


source to share


2 answers


You can put directives on your scrollable div that listen for an event scroll

and check if the top or bottom is reached.

So, using your HTML, your div will look like this:

<div exec-on-scroll-to-top="ctrl.handleScrollToTop"
     exec-on-scroll-to-bottom="ctrl.handleScrollToBottom"
     style="width:90%;height:150px;border:1px solid red;overflow:auto">
  <div ng-repeat="n in name">{{n.name}}</div>
</div>

      

Added new directives exec-on-scroll-to-top

and exec-on-scroll-to-bottom

. Each defines a function in your controller that should be executed when a specific event occurs that the directive checks.

exec-on-scroll-to-top

would look like this, just checking that the scrollable div property scrollTop

would be 0

:



myapp.directive('execOnScrollToTop', function () {

  return {

    restrict: 'A',
    link: function (scope, element, attrs) {
      var fn = scope.$eval(attrs.execOnScrollToTop);

      element.on('scroll', function (e) {

        if (!e.target.scrollTop) {
          console.log("scrolled to top...");
          scope.$apply(fn);
        }

      });
    }

  };

});

      

And it exec-on-scroll-to-bottom

will look like this (bearing in mind that the element is fully scrolled when its (scrollHeight - scrollTop) === clientHeight

):

myapp.directive('execOnScrollToBottom', function () {

  return {

    restrict: 'A',
    link: function (scope, element, attrs) {
      var fn = scope.$eval(attrs.execOnScrollToBottom),
          clientHeight = element[0].clientHeight;

      element.on('scroll', function (e) {
        var el = e.target;

        if ((el.scrollHeight - el.scrollTop) === clientHeight) { // fully scrolled
          console.log("scrolled to bottom...");
          scope.$apply(fn);
        }
      });
    }

  };

});

      

Here's a piece . Open your console to see how messages are logged as you scroll up or down.

+5


source


This is not an angular method, but you can wrap it in a directive that also allows for reuse:

Use Javascript event listener:

div.addEventListener('scroll', function(){
    if(this.scrollTop===0)
    //do your stuff

      



});

Make sure to use $apply

if you make any changes to scope variables inside this listener.

+1


source







All Articles