I'am using AngularJS and I use an ng-repeat
block. I want to use a unique/dynamic ng-model
name. The idea of this code is that when I click the buttom I increase the value of the textbox. The name of the parameters is correct in the debugger but the value is not changing. Below there is the code that I use but it is not working and I can not find why. Can anyone help me please?
<tr ng-repeat="item in resultShoppingCart track by $index">
<td class="price" ng-bind="item.unitPrice"><span></span></td>
<td class="qty">
<input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="Qty['{{$index}}']">
<a href=""><i class="fa fa-plus" ng-click="addQuantity(item.quantity, item.productId, $index)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
</td>
<td class="price" ng-bind="item.price"><span>$99.00</span></td>
<td class="action"><a ng-click="delete(userId,item.productId)">Delete item</a></td>
</tr>
And my controller.
$scope.addQuantity = function (currentQuantity, productId, i) {
$scope["Qty['" + i + "']"] = currentQuantity + 1;
alert($scope["Qty['" + i + "']"]);
}
Since the result of '{{$index}}'
expression will be '{{$index}}'
itself. So you have to change the expression to Qty[$index]
rather than using Qty['{{$index}}']
inside ng-model
, so that interpolation will evaluate it correctly.
But I would recommend to use item.quantity
, which ultimately going to be unique itself. No need to maintain separate object (as such I don't see any reason save Quantity in separately).
<td class="qty">
<input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="item.quantity" >
<a href=""><i class="fa fa-plus" ng-click="addQuantity(item)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
</td>
Code
$scope.addQuantity = function (item) {
item.quantity = item.quantity + 1;
}