简体   繁体   中英

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 () { 
   ...
})

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

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 .

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM