Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment and decrement a value in angularjs?

I have one value initially - let's call it x. Selecting the increment button should increase "+1" to the value. If I select decrement, x should decrease by -1.

However, what actually happens is that when I press the increment button, it increases +1 but if i click decrement, it decreases -2. It should only be increased/decreased by 1 value only. Also don't require continuous iteration (count++ and count--). it would be better if "count" is taken as variable inside .js file, not mentioning it in html as ng-init="count=15" .

JsBin

<div ng-controller="CounterController">
  <button ng-click="count = {{count}}+1" ng-init="count=15">
    Increment
  </button>
  count: {{count}}

  <button ng-click="count = {{(count) - 1}}">
    Decrement
  </button>
<div>
like image 359
madhu kumar Avatar asked Dec 01 '14 11:12

madhu kumar


2 Answers

"Exactly 1 value to be incremented or decremented"

<div ng-controller="CounterController">
  <button ng-click="increment();">
    Increment
  </button>
  count: {{count}}

  <button ng-click="decrement();">
    Decrement
  </button>
<div>

Controller:

angular.module('myApp', [])
.controller('CounterController', function($scope) {
  var incremented = false;
  var decremented = false;
  $scope.count = 15;

  $scope.increment = function() {
    if (incremented) { return; }
    $scope.count++;
    incremented = true;
  };
  $scope.decrement = function() {
    if (decremented) { return; }
    $scope.count--;
    decremented = true;
  };
});

If you want the user to be able to repeatedly do this, then...

angular.module('myApp', [])
.controller('CounterController', function($scope) {
   $scope.count = 15;
   var max = $scope.count + 1;
   var min = $scope.count - 1;

  $scope.increment = function() {
    if ($scope.count >= max) { return; }
    $scope.count++;
  };
  $scope.decrement = function() {
    if ($scope.count <= min) { return; }
    $scope.count--;
  };
});

JS Fiddle - http://jsfiddle.net/HB7LU/8673/

like image 171
Steven Keith Avatar answered Oct 26 '22 13:10

Steven Keith


Simply this should work,

<div>
    <button ng-click="count = count+1" ng-init="count=15">
        Increment
    </button>
    count: {{count}}

    <button ng-click="count = count - 1">
        Decrement
    </button>
<div>
like image 28
kriznaraj Avatar answered Oct 26 '22 12:10

kriznaraj