Javascript 如何在 AngularJS 指令中绑定元素上的滚动事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44100053/
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
How to bind scroll event on element in AngularJS directive
提问by Arri
How can I bind scroll event on element in AngularJS directive ?
如何在 AngularJS 指令中的元素上绑定滚动事件?
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) .
我在 $window 上绑定滚动,但现在我需要将其更改为此类 ".body-wrapper" (angular.element(document.queryselector(.body-wrapper)) 不起作用) 。
Any ideas ?
有任何想法吗 ?
angular.element($window).bind("scroll", function () {
...
})
回答by Ziv Weissman
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.
将事件更改为“鼠标滚轮”即可解决问题。
回答by squgeim
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.
指令是在 Angularjs 中访问 DOM 元素的首选和更清晰的方法,而不是angular.element.
回答by Adi
mousewheelevent triggers the scroll event to the window than a scrollevent.
mousewheel事件触发滚动事件到窗口而不是滚动事件。
angular.element($window).bind('mousewheel', function () {
// enter code here
}
回答by heriberto perez
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:
然后你可以在你的 Html 中使用它:
<div scroll-directive="">a long list goes here</div>

