Sunday 15 June 2014

html - How to calculate the total sum of items in array element using AngularJS -



html - How to calculate the total sum of items in array element using AngularJS -

i have table has column named priced,what want calculate total cost of items.what tried doesn't add together total cost displays same values in table row.i have included link jsbin.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> <html> <div ng-app> <div ng-controller="shoppingcartctrl"> <br /> <table border="1"> <thead> <tr> <td>name</td> <td>price</td> <td>quantity</td> <td>remove item</td> </tr> </thead> <tbody> <tr ng-repeat="item in items"> <td>{{item.name}}</td> <td>{{item.price}}</td> <td>{{item.quantity}}</td> <td><input type="button" value="remove" ng-click="removeitem($index)" /></td> </tr> </tbody> </table> <br /> <div>total price: {{totalprice()}}</div> <br /> <table> <tr> <td>name: </td> <td><input type="text" ng-model="item.name" /></td> </tr> <tr> <td>price: </td> <td><input type="text" ng-model="item.price" /></td> </tr> <tr> <td>quantity: </td> <td><input type="text" ng-model="item.quantity" /></td> </tr> <tr> <td colspan="2"><input type="button" value="add" ng-click="additem(item)" /> </td> </tr> </table> </div> </div> </html> function shoppingcartctrl($scope) { $scope.items = [ {name: "soap", price: "25", quantity: "10"}, {name: "shaving cream", price: "50", quantity: "15"}, {name: "shampoo", price: "100", quantity: "5"} ]; $scope.additem = function(item) { $scope.items.push(item); $scope.item = {}; }; $scope.totalprice = function(){ var total = 0; for(count=0;count<$scope.items.length;count++){ total +=$scope.items[count].price + $scope.items[count].price; } homecoming total; }; $scope.removeitem = function(index){ $scope.items.splice(index,1); }; }

http://jsbin.com/mapigagawa/1/edit?html,js,output

your problem defined cost , quantity string , not numbers. have 2 choices

define cost , quantity numbers , not strings, improve solution

use parseint or parsefloat during calculation

function shoppingcartctrl($scope) { $scope.items = [ {name: "soap", price: 25, quantity: 10}, {name: "shaving cream", price: 50, quantity: 15}, {name: "shampoo", price: 100, quantity: 5} ]; $scope.additem = function(item) { $scope.items.push(item); $scope.item = {}; }; $scope.totalprice = function(){ var total = 0; for(count=0;count<$scope.items.length;count++){ total += $scope.items[count].price + $scope.items[count].price; } homecoming total; }; $scope.removeitem = function(index){ $scope.items.splice(index,1); }; }

html angularjs

No comments:

Post a Comment