javascript - 如何使用 angularjs 鼠标事件在鼠标按住时连续增加值?

标签 javascript jquery angularjs

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

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

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

最佳答案

根据我的理解,想要在按下鼠标+按住时不断增加值。

你的代码

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

点击时只会将值增加一。

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

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

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

此外,更新 setTimeout 中的值不会直接反射(reflect)。您必须使用$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>

关于javascript - 如何使用 angularjs 鼠标事件在鼠标按住时连续增加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34783369/

相关文章:

jQuery:检测对不是原始类的已更改类名的点击

javascript - 将我的数据 json 放入其他文件中并将其调用到我的 Controller 中

javascript - 无法在 angularjs 中更改我的表数据?

javascript - 无法通过sequelize 使用 es6 导入和导出

jquery - 如何将 livequery 替换为 on?

javascript - 显示点击返回后HTML显示的最后状态

javascript - 条件事件监听器

javascript - 获取 Emberjs 中点击的元素的值

javascript - 无法使用nodejs访问json对象的属性

javascript - 如何在 `rot-js` Canvas 上绘制其他形状或线条?