Reputation:
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
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
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
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!');
})
});
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.
Upvotes: 12
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