您的位置:首页 > Web前端 > AngularJS

angularJs 购物车模型

2015-11-04 15:47 232 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="vendor/bootstrap3/css/bootstrap.min.css" />
<script type="text/javascript" src="vendor/angularjs/angular.min .js"></script>
<script type="text/javascript">
var cartController = function($scope){
$scope.cart= [
{
id:1000,
name:"iphone6s",
quantity:3,
price:6088
},
{
id:2000,
name:"iphone5",
quantity:30,
price:5088
},
{
id:3000,
name:"imac",
quantity:10,
price:23000
},
{
id:4000,
name:"ipad",
quantity:6,
price:6900
}
]
/*计算总价*/
$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 = findIndex(id);
if(index!== -1){
$scope.cart.splice(index,1);
}
}
$scope.add = function(id){
var index = findIndex(id);
if(index !== -1){
++$scope.cart[index].quantity;
}
}
$scope.reduce = function(id){
var index = findIndex(id);
if(index !== -1){
var item = $scope.cart[index];
if(item.quantity>1){
--item.quantity;
}else{
var returnkey = confirm("从购物车中删除该商品吗?");
if(returnkey){
$scope.remove(id);
}
}
}
}
/*
*查找元素索引
*/
var findIndex = function(id){
var index = -1;
angular.forEach($scope.cart,function(item,key){
if(item.id === id){
index = key;
return;
}
})
return index;
}
/* 监听表单数字大小 小于1  提示是否删除 */
$scope.$watch("cart",function(newValue,oldValue){
angular.forEach(newValue,function(item,key){
if(item.quantity<1){
var returnkey = confirm("从购物车中删除该商品吗?");
if(returnkey){
$scope.remove(item.id);
}else{
item.quantity=oldValue[key].quantity;
}

}
})
},true)
}
</script>
</head>
<body ng-app>
<div class="container" ng-controller="cartController">
<table class="table" ng-show="cart.length">
<thead>
<tr>
<th>产品编号</th>
<th>产品名字</th>
<th>购买数量</th>
<th>产品单价</th>
<th>产品总价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in cart">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>
<button type="button" class="btn btn-primary" ng-click="reduce(item.id)">-</button>
<input type="text" value="{{totalQuantity()}}" ng-model="item.quantity" maxlength="4"/>
<button type="button" class="btn btn-primary" ng-click="add(item.id)">+</button>
</td>
<td>{{item.price}}</td>
<td>{{item.price * item.quantity}}</td>
<td>
<button type="button" ng-click="remove(item.id)" class="btn btn-danger">移除</button>
</td>
</tr>
<tr>
<td>总购买价</td>
<td>{{totalPrice()}}</td>
<td>总购买数量</td>
<td>
{{totalQuantity()}}
</td>
<td colspan="2">
<button type="button" class="btn btn-danger" ng-click="cart={}">清空购物车</button>
</td>
</tr>
</tbody>
</table>
<p ng-show="!cart.length"> 您的购物车为空!</p>
</div>

</body>
</html>


页面展示效果:



-------------the end---------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: