<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://code.angularjs.org/1.2.5/angular.min.js"></script>
<style>
table{
border-collapse: collapse;
}
table tr:nth-child(even){
background-color: #888888;
}
table tr:nth-child(odd){
background-color: #cccccc;
}
th,td{
width: 15%;
text-align: center;
}
table tr td input{
width: 50px;
text-align: center;
}
</style>
</head>
<body>
<h3>我的购物车</h3>
<table ng-app="myApp" ng-controller="myCtrl">
<tr>
<th>排序</th>
<th>商品</th>
<th>价格/元</th>
<th>购买数量</th>
<th>小计/元</th>
<th>操作</th>
</tr>
<tr ng-repeat="x in list">
<td>{{$index+1}}</td>
<td>{{x.goods}}</td>
<td>{{x.price}}</td>
<td><button ng-click="reduce($index)">-</button><input type="text" ng-model="x.quantity"><button ng-click="add($index)">+</button></td>
<td>{{x.price*x.quantity}}</td>
<td><button ng-click="remove()">删除</button></td>
</tr>
<tr></tr>
</table>
<span>总价:</span><span ng-click="totalPrice()"></span>
<span>购买数量:</span><span ng-click="totalQuantity()"></span>
<button ng-click="removeAll()">清空购物车</button>
</body>
<script type="text/javascript">
var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
//商品数组
$scope.list=[
{ goods:'土豆',price:12,quantity:2},
{ goods:'西红柿',price:12,quantity:2},
{ goods:'茄子',price:12,quantity:2},
{ goods:'黄瓜',price:12,quantity:2},
{ goods:'胡萝卜',price:12,quantity:2}
];
//商品减少
$scope.reduce=function(index){
if( $scope.list[index].quantity>1){
$scope.list[index].quantity--;
}
else{
$scope.remove(index);
}
};
//商品增加
$scope.add=function(index){
$scope.list[index].quantity++;
};
//删除单个商品
$scope.remove=function(index){
if( confirm('您将要删除此项')) {
$scope.list.splice(index, 1);
}
};
//购买总价
$scope. totalPrice=function (){
var allprice = 0;
for(var i = 0 ; i <$scope.list.length;i++ ){
allprice += $scope.list[i].quantity * $scope.list[i].price;
}
return allprice;
}
//购买总数量
$scope.totalQuantity=function(){
var allnums = 0;
for(var i = 0 ; i <$scope.list.length;i++ ){
allnums += $scope.list[i].quantity;
}
return allnums;
}
//清空购物车
$scope.removeAll= function (){
if(confirm('您将要清空购物车')){
$scope.list=[];
}
}
});
</script>
</html>
angularjs编写购物车无法计算总价以及清除购物车问题