如何使用 angularjs 鼠标事件在鼠标保持时连续增加值

How to increment value continuously on mouse hold using angularjs mouse events?

本文关键字:鼠标 连续 增加值 何使用 angularjs 事件      更新时间:2023-09-26

我想连续递增值,直到使用 angularjs 将鼠标按住按钮。

<button class="btn btn-primary" ng-click="add('increase');"></button>
$scope.add = function(operation) {
  bill.quantity += 1;
}

根据我的理解,什么想要在mouse pressed + hold上不断增加价值.

您的代码

$scope.add = function(operation) {
  bill.quantity += 1;
}

只会在单击时将值增加一个。

对于您想要实现的目标,您必须有 2 个事件。

  • 首先,何时开始更新(ng-mousedown)。
  • 第二,何时停止更新(ng-mouseup)。

此外,事件仅触发一次,因此您需要使用setTimeout及时递增。

此外,更新setTimeout中的值不会直接反映。你将不得不使用 $scope.$apply() .参考以下帖子:AngularJS 输入字段未从控制器内的 setTimeout 更新

演示

JSFiddle.

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
  var interval = null;
  $scope.bill = {
    quantity: 0
  };
  $scope.add = function(newVal) {
    console.log("Add");
    initInterval(newVal);
  }
  function initInterval(newVal) {
    if (!interval) {
      console.log("Interval start");
      interval = setInterval(function() {
        $scope.$apply(function() {
          $scope.bill.quantity += newVal;
        });
      }, 1000);
    }
  }
  $scope.clearInterval = function() {
    console.log("Interval cleared");
    if (interval) {
      window.clearInterval(interval);
      interval = null;
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-controller="MyCtrl">
  <p>{{bill.quantity}}</p>
  <button class="btn btn-primary" ng-mousedown="add(1);" ng-mouseup="clearInterval()">Increment</button>
  <button class="btn btn-primary" ng-mousedown="add(-1);" ng-mouseup="clearInterval()">Decrement</button>
</div>