可实现数量加减,清空购物车,总价和总数计算
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div id="container" ng-app="myApp" ng-controller="myCtrl">
<table class="table table-striped" ng-show="cart.length">
<tr>
<th>产品编号</th>
<th>产品名称</th>
<th>产品数量</th>
<th>产品单价</th>
<th>产品总格</th>
<th>操作</th>
</tr>
<tr ng-repeat="item in cart">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>
<button type="button" class="btn btn-info" ng-click="subtract(item.id)">-</button>
<input type="number" min="1" ng-model="item.quantity">
<button type="button" class="btn btn-info" ng-click="add(item.id)">+</button>
</td>
<td>{{item.price}}</td>
<td>{{item.price*item.quantity}}</td>
<td><button type="button" class="btn btn-danger" ng-click="remove(item.id)">移除</button></td>
</tr>
<tr>
<td>产品总数</td>
<td>{{totalQuantity()}}</td>
<td>产品总价</td>
<td>{{totalPrice()}}</td>
<td colspan="2"><button type="button" class="btn btn-danger" ng-click="cart={}">清空购物车</button></td>
</tr>
</table>
<p ng-show="!cart.length">购物车为空</p>
</div>
</body>
<script>
var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.cart=[
{id:4561,name:"AJAX",quantity:1,price:4800},
{id:4452,name:"jSon",quantity:4,price:5600},
{id:8793,name:"angular",quantity:1,price:8900},
{id:1464,name:"vue",quantity:10,price:4600},
];
/*
*总价
*/
$scope.totalPrice=function(){
var total=0;
angular.forEach($scope.cart,function(item){
total+=item.price*item.quantity;
});
return total;
}
/*
*总数
*/
$scope.totalQuantity=function(){
var total=0;
angular.forEach($scope.cart,function(item){
total+=item.quantity;
});
return total;
}
/*
*删除
*/
$scope.remove=function(id){
var index=-1;
angular.forEach($scope.cart,function(item,key){
if(item.id==id){
index=key;
}
});
if(index!==-1){
$scope.cart.splice(index,1);
}
}
/*
*找到索引
*/
var find=function(id){
var index=-1;
angular.forEach($scope.cart,function(item,key){
if(item.id==id){
index=key;
return;
}
});
return index;
}
/*
*数量加一
*/
$scope.add=function(id){
var index=find(id);
if(index!==-1){
++$scope.cart[index].quantity;
}
}
/*
*数量减一
*/
$scope.subtract=function(id){
var index=find(id);
if(index!==-1){
if($scope.cart[index].quantity>1){
$scope.cart[index].quantity--;
}else{
var i=confirm("是否删除此商品?");
if(i){
$scope.remove(id);
}
}
}
}
$scope.$watch('cart',function(oldValue,newValue){
console.log(oldValue);
//oldValue是cart数组
angular.forEach(newValue,function(item,key){
console.log(item);
//item代表cart数组的四个对象/元素
if(item.quantity<1){
var i=confirm("是否删除此商品?");
if(i){
$scope.remove(item.id);
}else{
item.quantity=oldValue[key].quantity;
}
}
});
},true);
});
</script>
</html>
效果图如下: