I've been struggling with this problem for a while now - I can't seem to find a solution. The issue is that I have an empty object that gets filled with products when clicked on (ng-click="AddProduct(product)")
. Each product in the array has a property called subtotal, which is always an integer. My goal is to update the total every time a product is added to the array. Additionally, after all the products are added, the user should be able to add or subtract either a fixed amount or a percentage from the total (like adding extra charges or applying a discount). To achieve this functionality, I created a total function as shown below:
$scope.total = function () {
var total = 0;
angular.forEach($scope.orderContent.products, function (s) {
total += parseFloat(s.subtotal);
if ($scope.orderContent.totals.extras.ServiceCharge) {
total = total + $scope.orderContent.totals.extras.ServiceCharge;
}
if ($scope.orderContent.totals.extras.ServiceChargePercentage) {
total = (total / 100) * $scope.orderContent.totals.extras.ServiceChargePercentage + total;
}
});
total = total.toFixed(2);
return total;
};
The problem I'm facing is inconsistency - sometimes the above code works perfectly (such as when I finish adding a product and then adjust the total), but other times it doesn't work as expected (for instance, when I add a value, delete it, and add another one, the original value seems to linger and gets added together with the second value).
What could I possibly be missing here?
EDIT: I've created a Plunker to showcase the issue.