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;
}
cheralathan
  • 572
  • 5
  • 14
  • Can you show us what have you achieved so far? – Rajesh Jan 14 '16 at 06:57
  • 4
    You can use timeout to "count" the possible clicks made when the user holds the mouse down. Here's a sample code. http://stackoverflow.com/questions/25180332/how-can-i-listen-for-a-click-and-hold-in-angularjs – Wreeecks Jan 14 '16 at 06:59
  • 2
    `ng-lick` .... LAWL!!! Also, this will only increment once. – Rajesh Jan 14 '16 at 07:04

1 Answers1

3

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.

  • First, when to start update (ng-mousedown).
  • Second, when to stop update (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

Demo

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>
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79