I want to increment value continuously until mouse hold on a button using angularjs.
<button class="btn btn-primary" ng-click="add('increase');"></button>
$scope.add = function(operation) {
bill.quantity += 1;
}
I want to increment value continuously until mouse hold on a button using angularjs.
<button class="btn btn-primary" ng-click="add('increase');"></button>
$scope.add = function(operation) {
bill.quantity += 1;
}
Per my understanding, what want to continuously increment value on mouse pressed + hold
.
Your code
$scope.add = function(operation) {
bill.quantity += 1;
}
will just increment value by one on click.
For what you want to achieve, you have to have 2 events.
ng-mousedown
).ng-mouseup
).Also, events are fired only once, so you need to use setTimeout
to increment in timely fashion.
Also, updating value in a setTimeout
does not reflect directly. You will have to use $scope.$apply()
. Refer following post for reference: AngularJS Input field not updating from setTimeout inside controller
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>