如何在 AngularJS 指令中的元素上绑定滚动事件
How to bind scroll event on element in AngularJS directive
如何在 AngularJS 指令中的元素上绑定滚动事件?
我在 $window 上绑定滚动条,但现在我需要将其更改为 class ".body-wrapper" (angular.element(document.queryselector (.body-wrapper)) 不起作用)。
有什么想法吗?
angular.element($window).bind("scroll", function () {
...
})
您通常会为此制定一个新指令。
app.directive('scroll', [function() {
return {
link: function (scope, elem, attrs) {
elem.on('scroll', function (e) {
// do your thing
});
})
}
}]);
现在,在需要添加滚动事件的地方使用此指令。
<div class='.body-wrapper' scroll></div>
指令是访问 Angularjs 中 DOM 元素的首选和更简洁的方法,而不是 angular.element
.
没有理由它不工作。
这个简单的例子表明它确实如此-
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
angular.element(document.querySelector('.myDiv')).bind('scroll', function(){
alert('scrolling is cool!');
})
});
如果由于某种原因无法正常工作,post 完整代码。
讨论后编辑:
最终问题出在 "scroll" 的特定事件上,它可能与另一个事件发生冲突。
将事件更改为 "mousewheel" 成功了。
mousewheel事件触发的滚动事件比scroll事件要window。
angular.element($window).bind('mousewheel', function () {
// enter code here
}
我找到的最干净的方法是:
(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);
}
};
};
})();
然后您可以在 Html 中使用它:
<div scroll-directive="">a long list goes here</div>
如何在 AngularJS 指令中的元素上绑定滚动事件?
我在 $window 上绑定滚动条,但现在我需要将其更改为 class ".body-wrapper" (angular.element(document.queryselector (.body-wrapper)) 不起作用)。
有什么想法吗?
angular.element($window).bind("scroll", function () {
...
})
您通常会为此制定一个新指令。
app.directive('scroll', [function() {
return {
link: function (scope, elem, attrs) {
elem.on('scroll', function (e) {
// do your thing
});
})
}
}]);
现在,在需要添加滚动事件的地方使用此指令。
<div class='.body-wrapper' scroll></div>
指令是访问 Angularjs 中 DOM 元素的首选和更简洁的方法,而不是 angular.element
.
没有理由它不工作。
这个简单的例子表明它确实如此-
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
angular.element(document.querySelector('.myDiv')).bind('scroll', function(){
alert('scrolling is cool!');
})
});
如果由于某种原因无法正常工作,post 完整代码。
讨论后编辑:
最终问题出在 "scroll" 的特定事件上,它可能与另一个事件发生冲突。
将事件更改为 "mousewheel" 成功了。
mousewheel事件触发的滚动事件比scroll事件要window。
angular.element($window).bind('mousewheel', function () {
// enter code here
}
我找到的最干净的方法是:
(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);
}
};
};
})();
然后您可以在 Html 中使用它:
<div scroll-directive="">a long list goes here</div>