user6644024
user6644024

Reputation:

How to bind scroll event on element in AngularJS directive

How can I bind scroll event on element in AngularJS directive ?

I bind scroll on $window, but now i need to change it to this class ".body-wrapper" (angular.element(document.queryselector(.body-wrapper)) doesn't work) .

Any ideas ?

angular.element($window).bind("scroll", function () { 
   ...
})

Upvotes: 13

Views: 58586

Answers (4)

Heriberto Magaña
Heriberto Magaña

Reputation: 898

The cleanest way I have found is:

(function() {
  angular
  .module('yourAppName')
  .directive('scrollDirective', ['$window', scrollDirective])

  function scrollDirective($window) {
    return {
      link: function (scope, element, attrs) {
        var handler;
        $window = angular.element($window);

        handler = function() {
          console.log('scrolling....')
        };

        $window.on('scroll', handler);
      }
    };

  };

})();

then you can use it in your Html as:

 <div scroll-directive="">a long list goes here</div>

Upvotes: 4

Adi
Adi

Reputation: 139

mousewheel event triggers the scroll event to the window than a scroll event.

angular.element($window).bind('mousewheel', function () {  
  // enter code here  
}

Upvotes: 3

Ziv Weissman
Ziv Weissman

Reputation: 4536

No reason it shouldn't work.

This simple example shows it does-

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  angular.element(document.querySelector('.myDiv')).bind('scroll', function(){
      alert('scrolling is cool!');
    })
});

Plunker example

if for some reason it is not working, post full code.

Edit after discussion:

Eventually the problem is with the specific event for "scroll", it probably collides with another event.

Changing the event to "mousewheel" did the trick.

Working fiddle

Upvotes: 12

squgeim
squgeim

Reputation: 2351

You would normally make a new directive for that.

app.directive('scroll', [function() {
  return {
    link: function (scope, elem, attrs) {
      elem.on('scroll', function (e) {
        // do your thing
      });
    })
  }
}]);

Now, use this directive where ever you need to add the scroll event.

<div class='.body-wrapper' scroll></div>

Directives are the preferrd and cleaner approach to accessing DOM elements in Angularjs, instead of angular.element.

Upvotes: 11

Related Questions