How to bind an element scroll event in AngularJS directive
How to bind element scroll event in AngularJS directive?
I bind the scroll to $ 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 () {
...
})
source to share
There is no reason why it shouldn't work.
This simple example shows what 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 it doesn't work for some reason, please write the complete code.
Edit after discussion:
At the end of the day, the problem is with a specific event for the "scroll", it probably collides with a different event.
Changing the event to "mousewheel" did the trick.
source to share
Typically, you create a new directive for yourself.
app.directive('scroll', [function() {
return {
link: function (scope, elem, attrs) {
elem.on('scroll', function (e) {
// do your thing
});
})
}
}]);
Now use this directive when you need to add a scroll event.
<div class='.body-wrapper' scroll></div>
Directives are the preferred and cleaner approach to accessing DOM elements in Angularjs instead of angular.element
.
source to share
The cleanest way I've found is this:
(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 like:
<div scroll-directive="">a long list goes here</div>
source to share