12

I have made a time conter which allows you to increase or decrease the time by clicking a button. I would like however that when I click and hold the button the value of the time would keep climbing.

So currently if you see my Plunkr each time I click the up button the value increases but I want this so when I hold the button down the value increases 1,2,3,4,5,6,7,8 until I release the button.

How could I achieve something like this?

Darshan P
  • 2,241
  • 18
  • 16
Daimz
  • 3,243
  • 14
  • 49
  • 76

1 Answers1

25

DEMO

<span class="time">{{ Time | timeFilter }}</span>
<div class="btn-group btn-group-sm">
  <button class="btn btn-default" ng-mousedown='mouseDown()' ng-mouseup="mouseUp()">
    <i class="fa fa-caret-up"></i>
  </button>
  <button class="btn btn-default" ng-click="Time = Time - 1">
    <i class="fa fa-caret-down"></i>
  </button>
</div>

Use ng-mouseDown and ng-mouseup directive with $interval

app.directive('time', function ($interval) {
   return {
      templateUrl: 'time.html',
      restrict: 'E',
      scope: {
        Time: '=value'
      },
      link: function (scope, element, attrs) {
        element.addClass('time');

        var promise;      
        scope.mouseDown = function() {
          if(promise){
             $interval.cancel(promise);
          }
          promise = $interval(function () { 
            scope.Time++;
          }, 100);

        };

        scope.mouseUp = function () {
           $interval.cancel(promise);
           promise = null;
        };
     }
  };
});
CularBytes
  • 9,924
  • 8
  • 76
  • 101
Darshan P
  • 2,241
  • 18
  • 16
  • This is perfect thanks, Just one quick question. Does $interval simply cause the function to keep looping? – Daimz Aug 26 '14 at 23:26
  • Yes, every 100 milliseconds in this example. – Darshan P Aug 27 '14 at 15:30
  • 11
    If the mouse leaves the element while the mouse button is down, when the mouse button comes back up, the interval will not be cancelled. To deal with this, you could add `ng-mouseleave='mouseUp()'` – mjhasbach Aug 19 '15 at 17:34
  • Is there a solution for doing this with touch? I've tested it on a lenovo mobile device but unfortunately this doesn't work. – FRules Dec 12 '16 at 07:44
  • Try touch start and touch end events. – Darshan P Dec 12 '16 at 22:48
  • I've used this http://stackoverflow.com/a/26176810/2901207 touchEnd directive to trigger mouseUp again. Mouse down gets fired on touch and hold, mouse up doesn't, so we only need to cancel the interval on mouse up. – CularBytes Dec 22 '16 at 10:10