Javascript AngularJS 中的滚动事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26588300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scroll event in AngularJS
提问by Tream
I have a div with a scrollbar in it. Now I want to get an event, that triggers every time, the user scrolls.
我有一个带有滚动条的 div。现在我想获得一个事件,每次用户滚动时都会触发。
Is that possible in AngularJS, or do I have to use jQuery for that?
这在 AngularJS 中是可能的,还是我必须为此使用 jQuery?
Edit:I came up with following so far:
编辑:到目前为止我想出了以下内容:
// JS
.directive('scroll', function() {
return function(scope, element, attrs){
angular.element(element).bind("scroll", function(){
console.log(1);
});
};
});
// HTML
<div class="wrapper" style="height: 1550px" scroll>
[...]
</div>
But that does not work (I don't see any logs in my Firebug-Console).
但这不起作用(我在 Firebug 控制台中没有看到任何日志)。
回答by Sergey NN
Solution for Angular 1.6:
Angular 1.6 的解决方案:
.directive("scroll", function () {
return {
link: function(scope, element, attrs) {
element.bind("wheel", function() {
console.log('Scrolled below header.');
});
}
}
})
})
Use "wheel" instead of "scroll". It takes me few hours to find.
使用“轮”而不是“滚动”。我需要几个小时才能找到。
回答by frankies
You would be using jquery for adding the event listener, and maybe inside an angularjs directive to attach it to an element.
您将使用 jquery 添加事件侦听器,并且可能在 angularjs 指令中将其附加到元素。
page.html:
页面.html:
<div my-scroller>
myscroller.js:
myscroller.js:
app.directive('myScroller', function(){
return {
restrict: 'A',
link: function(scope,elem,attrs){
$(elem).on('scroll', function(evt){
console.log(evt.offsetX + ':' + evt.offsetY);
});
}
}
});
Edit: of course you don't even need to use jquery. Angular's jqLite suffices for this, you would just call element without the jquery wrapping:
编辑:当然你甚至不需要使用 jquery。Angular 的 jqLite 就足够了,你只需调用 element 而不用 jquery 包装:
elem.on('scroll', ...
回答by Developer A
Sergey's answer helped me a little, but what ended up working for me was this:
谢尔盖的回答对我有所帮助,但最终对我有用的是:
.directive("scroll", function ($window) {
return {
link: function() {
angular.element($window).bind("wheel", function() {
console.log('Scrolling');
});
}
}
})

