laggingreflex
laggingreflex

Reputation: 34627

How to bind() to this mousewheel event that comes in directive form

There this mousewheel directive that I want to use: https://github.com/monospaced/angular-mousewheel

Its docs tells to either attach it to the element as an attribute or a class,

but I want to attach it to it in my own directive.

var myDirective = function() {
    return {
        link: function($scope, elem) {
            elem.bind('>>here<<', function(){});

How to do that?

Upvotes: 0

Views: 9624

Answers (3)

Elorfin
Elorfin

Reputation: 2497

Old question, but it can help someone reading this :

element[0].addEventListener('DOMMouseScroll', _onWheel, false ); // For FF and Opera
element[0].addEventListener('mousewheel', _onWheel, false ); // For others

function _onWhell(e) {
    // Do what you want here
}

We need to use element[0] because your original DOM element is wrapped into an another object.

Upvotes: 0

Marc Kline
Marc Kline

Reputation: 9409

Add the directive to your own directive's template:

.directive('mwTemplate', function(){
  return {
    restrict: 'AC',
    scope: {},
    controller: function($scope){
      $scope.scroll = function($event, delta, deltax, deltay) {
        console.log($event, delta, deltax, deltay);
      }
    },
    template: '<div msd-wheel="scroll($event, delta, deltax, deltay)">Scroll over top of me</div>'
  };
})

... or add it inside of your directive's compile function:

.directive('mwCompile', function(){
  return {
    restrict: 'AC',
    scope: {},
    compile: function(elem){
      elem.find('div').attr('msd-wheel', 'scroll($event, delta, deltax, deltay)');
    },
    controller: function($scope){
      $scope.scroll = function($event, delta, deltax, deltay) {
        console.log($event, delta, deltax, deltay);
      }
    },
    template: '<div>Scroll over top of me</div>' 
  };
})

Plunkr

Upvotes: 1

Michal Charemza
Michal Charemza

Reputation: 27012

I suspect that directive can't be used in the way you want. However, looking in the angular-mousewheel source, if you include Hamster.js, as it does, you can do something like:

link: function(scope, element) {
  var hamster = $window.Hamster(element[0]);
  hamster.wheel(function(e, delta, deltaX, deltaY) {
    // React to wheel event here
  });
}

Upvotes: 2

Related Questions