continously add or subtract value in Angular
by Faisal Khan Janjua
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
<span style='margin-left:{{bill.quantity}}px;'>{{bill.quantity}}</span>
<br>
<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>
CSS
div{
width:100%;
height:40px;
float:left;
display:block;
}
span{
width:auto;
height:16px;
float:left;
display:block;
background:#9F9;
}
JavaScript
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;
});
}, 20);
}
}
$scope.clearInterval = function (){
console.log("Interval cleared");
if(interval){
window.clearInterval(interval);
interval = null;
}
}
}