Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debounce with ngMouseover

I have this HTML div which uses the ngMouseover directive to get some data from the api via a function as follows:

Markup:

<div ng-mouseover="getData()">
</div> 

Controller:

$scope.getData = function() {
    //get data from api
}

Is there any way in which I can add a delay to the ngMouseover directive such that it is fired only after the cursor has stayed for a few seconds on the div? Just like it is with debounce in ngModelOptions.

like image 619
Tarun Dugar Avatar asked Dec 10 '15 08:12

Tarun Dugar


1 Answers

You can use a combination of onmouseenter and onmouseleave: If the mouse enters the element and doesn't leave for at least 2 seconds, then evaluate.

<div debounce-mouseover="getData()" stay-at-least="2"></div>

And the directive debounceMouseover is:

template: "<div ng-mouseenter="onEnter()" ng-mouseleave="onLeave()">",

link: function(scope, elem, attrs) {
  var stayAtLeast = attrs.stayAtLeast;
  var timer;

  scope.onEnter = function() {
    timer = $timeout(function() {
      scope.$eval(attrs.debounceMouseover);
    }, stayAtLeast);
  };

  scope.onLeave = function() {
    $timeout.cancel(timer);
  };
}

(that's the generic idea, actual implementation is left to you, if you need help let me know)

like image 179
floribon Avatar answered Nov 07 '22 16:11

floribon