<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>
你好我只是想问一下如何使用angularjs在我的购物车中添加我购买的总金额(myCart中的项目)。我根据自己的知识尝试了所有基础,但似乎没有任何反应。希望有人带我走过这一个。谢谢
答案 0 :(得分:1)
我做了一个说明这一点的人:https://plnkr.co/edit/tXtowcva1KeAmGeL6gut?p=preview
添加项目时,您可以确定价格:
$scope.addToCart = function(item) {
$scope.myCart.push(item);
$scope.amount += item.price;
};
答案 1 :(得分:0)
像其中一个选项一样:
$scope.getTotalAmount = function() {
var total = 0;
for(var i = 0; i < $scope.myCart.length; i++){
var product = $scope.myCart[i];
total += product.price;
}
return total;
};
然后用
做你需要的答案 2 :(得分:0)
getTotalAmount()
函数中的语法似乎有些偏差。试试这个:
$scope.getTotalAmount = function() {
var i = 0;
var total = 0.0;
for (i=0; i < $scope.myCart.length; i++) {
total += $scope.myCart[i].price;
}
return total;
};
答案 3 :(得分:0)
$scope.getTotalAmount = function() {
var i = 0,
sum = 0;
for (; i < $scope.myCart.length; i++) {
sum += (+$scope.myCart[i].price);
}
$scope.amount = sum;
};
此getTotalAmount函数应该可以使用,前提是您的项目中有数字作为价格,
$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 }
];