javascript 如何在 AngularJS 中监听单击并按住?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25180332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:07:44  来源:igfitidea点击:

How can I listen for a click-and-hold in AngularJS?

javascriptangularjsangularjs-directive

提问by Daimz

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 Plunkreach 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,8until I release the button.

因此,目前,如果每次我单击向上按钮时都会看到我的Plunkr,则该值会增加,但我希望如此,因此当我按住按钮时,该值会增加,1,2,3,4,5,6,7,8直到我松开按钮。

How could I achieve something like this?

我怎么能做到这样的事情?

回答by Darshan P

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

在 $interval 中使用 ng-mouseDown 和 ng-mouseup 指令

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;
        };
     }
  };
});