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

时间:2016-01-14 06:54:19

标签: javascript jquery angularjs

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

<button class="btn btn-primary" ng-click="add('increase');"></button>

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

1 个答案:

答案 0 :(得分:2)

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

您的代码

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

只会在点击时将值增加1。

对于你想要达到的目标,你必须有2个事件。

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

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

此外,更新setTimeout中的值并不直接反映。您必须使用$scope.$apply()。请参阅以下帖子以供参考:AngularJS Input field not updating from setTimeout inside controller

演示

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>