Patrickkx Patrickkx - 1 month ago 9
Javascript Question

AngularJS: Increment input's value

I have a button and an input in html:

<button ng-click="addQuantity()" class="btn btn-xs btn-info pull-right">+</button>
<input readonly type="text" value="{{ quantity || 1 }}" class="form-control totalQuantity pull-right"></input>


And the AngularJS code:

$scope.addQuantity = function(id){

}


I just want to increment the input.value (which default is 1), with every click on the button. I would to it by myself, but I don't know the most efficient way to do it.

If you have any hints for me, please share. Thank you!

Edit
The
id
is the
id
from ng-repeat:

<li class="list-group-item" ng-repeat="(id, product) in itemsToBuy">


The input is added with every repeat of li element.

Edit2: There's a fiddle with whole app: https://jsfiddle.net/scgsc7or/3/

Answer
<button ng-click="addQuantity(id)" class="btn btn-xs btn-info pull-right">+</button>
<input readonly type="text" value="{{product.quantity || 1}}" class="form-control totalQuantity pull-right"/>

Pass the id which serves as an array index to identify exact product in the addQuantity.

And just simply increment the quantity. If quantity is undefined - it is equal to 1, otherwise - increment

$scope.addQuantity = function(id){
    if(!$scope.itemsToBuy[id].quantity){
       $scope.itemsToBuy[id].quantity = 1;
    }else{
        $scope.itemsToBuy[id].quantity++;
    }
}
Comments