james managbanag james managbanag - 5 months ago 13
AngularJS Question

how to Add the total amount price of the items inside a Cart using angularjs

<div ng-app="myApp" ng-controller="namesController">

<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th> Items </th>
<th> Description </th>
<th> Price </th>
<th> action </th>
</tr>
</thead>

<tbody>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.price}}</td>
<td><button ng-click="addToCart(item)"> add to cart</button></td>
</tr>
</tbody>
</table>
</div>

<div class="row">
<div class="col-md-4">
<div class="myCart">
<div class="table">
<table class="table table-striped table-hover">
<thead>
<tr>
<th> Name </th>
<th> price </th>
</tr>
<thead>

<tbody>
<tr ng-repeat="item in myCart">
<td>{{item.name}}</td>
<td>{{item.price}}</td>
</tr>
</table>
</div>
</div>
</div>
</div>

<div class="myAmount">

Amount <input style="margin-left:350px;" type="text" name="myAmount" ng-value="amount" />

</div>



</div>

<script>

var app= angular.module('myApp', []);
app.controller('namesController', function($scope) {

//iniating the myCart object
$scope.myCart = [];

//items available in the table
$scope.items = [
{"name":"Milk", "description":"Milk for 5-12 years old", "price":"$23"},
{"name":"Beer", "description":"alcoholic beer", "price":"$5"},
{"name":"foods", "description":"foods", "price":"$8"}
];

$scope.addItems = function(item) {
$scope.items.push(item);
$scope.item = {};
};

$scope.addToCart = function(item) {
$scope.myCart.push(item);
};



$scope.getTotalAmount = function() {
var i = 0;
for (i=0; i<$scope.myCart.length; i++) {
$scope.myCart.item.price[i] * $scope.myCart.item.price[i];
}
};

$scope.amount = "0.00";





});

</script>

</body>
</html>


hello I just want to ask how to add the total amount I buy(items in myCart) in my Cart using angularjs. i tried all base in my knowledge but it seems nothing happens. hoping for someone to walk me through on this one. thank you

Answer

I did a plunker to illustrate this : https://plnkr.co/edit/tXtowcva1KeAmGeL6gut?p=preview

You can accumalate price when you add an item :

  $scope.addToCart = function(item) {
    $scope.myCart.push(item);     
    $scope.amount += item.price;
  };
Comments