0

Is there a way to catch the event scrolling the page does inside a controller? I have this on my component's controller $onInit:

$scope.$on('scroll', function() {
        console.log('Something something');
      });

I have only seen ways to do this using .bind() on a directive, like here: Scroll event in AngularJS

I have been lurking the official guide and I have found nothing.

2 Answers 2

0

You can add a attribute to the directive you linked to to take in a function from your controller to call when the scroll happens

.directive("scroll", function () {
return {
  restrict: 'A',
  scope : {
         "onScroll" : "&onScroll"
  },
  link: function(scope, element, attrs) {
      element.bind("wheel", function() {
         scope.onScroll();
      });
  }
}
});

Then in your template you would pass it in the attribute value

<ul scroll on-scroll="myController.onScroll()">
</ul>
Sign up to request clarification or add additional context in comments.

1 Comment

After some investigation, I found out that is impossible to catch this event outside a directive. This works as well: link: function(scope, element, attrs) { var theElementWithScroll = element[0]; theElementWithScroll.addEventListener('scroll', function() { scope.onScroll(); });
0

You can use angularJS's $element to do this properly.

angular.element($element).on('scroll', function() {
  console.log('Something something');
});

in a controller, $element is the element in the DOM that the controller is bound to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.