Reputation: 1439
UPDATED
I think
ng-init="currentQuantity=item.quantity"
simply prevents the ng-model currentQuantity from updating to the next incremented value. Are there any workarounds for this in the example below?
Can i for example target a currentQuantity model by index so i know which model i'm changing and not all of them at once?
I'm currently having issues with AngularJS. By the code beneath i'm adding products to a cart array:
QuantityChanged(product, currentQuantity);
Next i have a + button next to this input field which just adds +1 of the quantity of the product to the cart.
<button class="plus-button" ng-click="addToCart(product);">+</button>
My ng-model="currentQuantity" however only updates when using QuantityChanged(product,currentQuantity) but not when i'm using the ng-click="addToCart(product)" function.
If i look in my localstorage i see that the quantity of the cart is succesfully updated but when i look at the current input text field value of the ng-model: currentQuantity i see nothing is changed. When i refresh i'll see the correct value in the input field. Am i missing something obvious?
View:
<span ng-repeat="item in cart">
<span ng-if="item.id === product.id">
<input type="text" ng-change="QuantityChanged(product, currentQuantity);" ng-model="currentQuantity" ng-init="currentQuantity=item.quantity" class="product-aantal" />
</span>
</span>
<button class="plus-button" ng-click="addToCart(product);">+</button>
Some Controller Code (if necessary):
$scope.QuantityChanged = function (product, quantity) {
quantity = parseFloat(quantity, 6);
$scope.cart.forEach(function (item) {
if (item.id === product.id) {
if(item.quantity < quantity){
$scope.productCounter = $scope.productCounter + (quantity - item.quantity);
}
if(item.quantity > quantity){
$scope.productCounter = $scope.productCounter - (item.quantity - quantity);
}
item.quantity = quantity;
item.totalprice = parseFloat(item.price,6) * quantity;
}
});
this.saveProducts($scope.cart);
this.saveProductCounter($scope.productCounter);
};
$scope.addToCart = function (product) {
var found = false;
$scope.cart.forEach(function (item) {
if (item.id === product.id) {
item.quantity++;
$scope.productCounter++;
item.totalprice += parseFloat(item.price,6);
found = true;
}
});
if (!found) {
$scope.cart.push(angular.extend({quantity: 1, totalprice: parseFloat(product.price,6) }, product));
$scope.productCounter += 1;
}
this.saveProducts($scope.cart);
this.saveProductCounter($scope.productCounter);
};
Upvotes: 0
Views: 165
Reputation: 1463
It is related to the scope of the ng-repeat.
Change the currentQuantity to current.quantity and inside addToCart manipulate that value as well.
if (item.id === product.id) {
item.quantity++;
$scope.current.quantity++;
$scope.productCounter++;
item.totalprice += parseFloat(item.price,6);
found = true;
}
I must say that your logic is quite hard to understand, but that fixes the problem.
Upvotes: 1