how to get event when user scroll to top in angular js?

6k views Asked by At

could you please tell me how to get event when user scroll to top .Actually I am using ng-repeat in my example .I want to get event when user scroll to bottom and scroll to top .I have one div in which I used ng-repeat can we get event of top when user move to top after scrolling.Actually I need to show alert when user scroll to bottom and top of 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>
2

There are 2 answers

1
Frozen Crayon On

This is a non angular way, but you can wrap it up in a directive which also allows 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 the scope variables inside this listener.

0
MikeJ On

You could put directives on your scrollable div that listen to the scroll event and check for the top or bottom being reached.

So, using your HTML, your div would 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>

With new directives exec-on-scroll-to-top and exec-on-scroll-to-bottom added. Each specifies a function in your controller that should execute when the particular event the directive is checking for occurs.

exec-on-scroll-to-top would look like this, just checking for the scrollable div's scrollTop property to 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 exec-on-scroll-to-bottom would look like this (keeping in mind that an 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 plunk. Open the console to see messages getting logged when the scrolling reaches the top or bottom.