我想连续增加值,直到鼠标按住使用 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/