I'm building a project with angular and PHP. I have a "select" option which I can choose and it shows me all the "categories" I need and I need to select one. Then it can calculate the quantity of "products" when I pick a "category", but when I pick another "category" the total is no reset to 0 to count again it just counts more. Can someone please help?
this is my code:
Html:
<select ng-model="stockReport.selectedOption"
ng-change="computeTotal()" ng-options = "item.category_name for item in stockReport |
unique:'category_name'">
<option value="">בחר קטגוריה</option>
</select>
<div class="table-responsive">
<table class="customer-list table table-striped" >
<thead>
<tr >
<th class="Column-Header">קטגוריה</th>
<th class="Column-Header">קוד מוצר</th>
<th class="Column-Header">שם מוצר</th>
<th class="Column-Header">תיאור מוצר</th>
<th class="Column-Header">כמות במלאי</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in stockReport" ng-if = "item.category_name == stockReport.selectedOption.category_name"
ng-init="setTotals(item)">
<td>{{item.category_name}}</td>
<td>{{item.stock_id}}</td>
<td>{{item.product_name}}</td>
<td>{{item.description}}</td>
<td>{{item.quantity}}</td>
</tr>
</tbody>
<tfoot>
<tr class="bg-warning">
<td><font size="6">סך הכל מוצרים במלאי:</font></td>
<td><font size="6">{{total}}</font></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
Controller function that calculate:
$scope.total = 0;
$scope.setTotals = function(item){
// $scope.total = 0;
if (item){
$scope.total += parseInt(item.quantity);
console.log($scope.total);
return $scope.total;
}
}
Seems like you want the sum of all the quantity
of the table entry. Then you need to change the HTML code also
HTML:
<tbody>
<tr ng-repeat="item in stockReport" ng-if = "item.category_name == stockReport.selectedOption.category_name"
ng-init="setTotals(stockReport)">
<td>{{item.category_name}}</td>
<td>{{item.stock_id}}</td>
<td>{{item.product_name}}</td>
<td>{{item.description}}</td>
<td>{{item.quantity}}</td>
</tr>
</tbody>
OR
<select ng-options="......" ng-change="setTotals(stockReport)"></select> //this is better option and remove ng-init
JS:
$scope.setTotals = function(totalItem){
$scope.total = 0;
for(var item in totalItem){
if (totalItem[item] && (totalItem[item].category_name == $scope.stockReport.selectedOption.category_name)){
$scope.total += parseInt(totalItem[item].quantity);
console.log($scope.total);
return $scope.total;
}
}
}