繁体   English   中英

如何在AngularJS指令中绑定元素上的scroll事件

[英]How to bind scroll event on element in AngularJS directive

如何在AngularJS指令中绑定元素上的scroll事件?

我绑定$ window上的滚动,但现在我需要将它更改为此类“.body-wrapper”(angular.element(document.queryselector(.body-wrapper))不起作用)。

有任何想法吗 ?

angular.element($window).bind("scroll", function () { 
   ...
})

没理由它不应该工作。

这个简单的例子表明它 -

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  angular.element(document.querySelector('.myDiv')).bind('scroll', function(){
      alert('scrolling is cool!');
    })
});

Plunker的例子

如果由于某种原因它无法正常工作,请发布完整代码。

讨论后编辑:

最终问题是“滚动”的特定事件,它可能与另一个事件发生冲突。

将事件更改为“鼠标滚轮”就可以了。

工作小提琴

你通常会为此制定新的指令。

app.directive('scroll', [function() {
  return {
    link: function (scope, elem, attrs) {
      elem.on('scroll', function (e) {
        // do your thing
      });
    })
  }
}]);

现在,在需要添加scroll事件的地方使用此指令。

<div class='.body-wrapper' scroll></div>

指令是访问Angularjs中DOM元素而不是angular.element的首选和更简洁的方法。

mousewheel事件触发滚动事件到窗口而不是滚动事件。

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM