Liam Chapman Liam Chapman - 1 month ago 17
AngularJS Question

Angular JS not firing scroll event

I've started building my first project with Angular 1.5.x. So far so good.

However, I've recently been trying to do something super simple and log the window position/event on scroll. I've tried various approaches such as directives, binding events, jquery and nothing appears to be getting logged in the console.

Typically in raw javascript I would do something simple such as:

window.onscroll = function (e) {
console.log(e);
}


I've tried updating the code to look something like this in my controller:

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


It does nothing. If I change the event to a click or resize it responds. But scrolling does nothing. It's been really frustrating.

I've tried using a directive and i've had the same result. Nothing.

Angular appears to remove the scroll event or override it in someway. I'm hoping there's an obvious solution or just another attribute or approach I need to do.

Many thanks for taking the time to look into my question.

I'd really appreciate any help and advice anybody can offer.

zee zee
Answer

Take a look here http://plnkr.co/edit/FL06BgnmOpgVXNecB3mB?p=preview. Scroll through the HTML page and open up your console, you will see some output being printed. Notice in script.js that $window is a dependency injection.

app.directive("scroll", function ($window) {
  return function(scope, element, attrs) {
    angular.element($window).bind("scroll", function(e) {
      console.log(e);
      console.log(this.pageYOffset);
      scope.$apply();
    });
  };
});