Sudarshan Kalebere Sudarshan Kalebere - 3 months ago 112
AngularJS Question

Plus minus with single textbox in angularjs

I have two buttons and one text box I want, quantities to be increamented by 1 on click of +plus button and decremented by 1 on click of -minus button. But when it reaches to less than 0 or say 0 the decrement button should be disabled. I have this code here
PLunker

My html code

<form id='myform' >
<button ng-click="increment()" class='qtyminus'>-</button>
<input ng-modal="item.qty" type='text' name='quantity' value='0' class='qty' />
<button ng-click="decrement()" >+</button>
</form>


My js code

$scope.increment = function () {
alert('hi');
$scope.item.qty++;
};
$scope.decrement = function () {
$scope.item.qty--;
};

Answer
  • Use ng-diabled directive
  • Correct ty typo @ ng-modal, it is ng-model

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.qty = 10;
  $scope.increment = function() {
    $scope.qty++;
  };
  $scope.decrement = function() {
    $scope.qty--;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form id='myform' ng-app="myApp" ng-controller="myCtrl">
  <button ng-click="decrement()" class='qtyminus' ng-disabled="qty==0">-</button>
  <input ng-model="qty" type='text' name='quantity' class='qty' />
  <button ng-click="increment()">+</button>
</form>