我的购物车 多选框操作

这篇博客展示了如何使用AngularJS实现一个购物车的功能,包括添加商品、删除商品、清空购物车、计算商品总数和总价。通过ng-repeat指令遍历商品列表,并结合ng-model双向绑定实现数量修改,ng-change监听数量变化,ng-click处理移除和清空操作。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="js/angular.min.js" ></script>
<script>

var myApp = angular.module("myApp",[]);

myApp.controller("myCrtl",function($scope,$http){

//自定义数据
$scope.list = [
{ gid: 001, gname: "手机", gnum: 3,gprice: 1000, gcount: 3000 },
{ gid: 002, gname: "电脑", gnum: 3, gprice: 2000, gcount: 6000 },
{ gid: 003, gname: "电视", gnum: 6, gprice: 500, gcount: 3000 }
]

//删除方法
$scope.remove = function(index){
if(confirm("是否确认移除?")){
$scope.list.splice(index,1);
}
}

//清空购物车的方法
$scope.removes = function(){
if(confirm("确定要清空购物车?")){
$scope.list = [];
}
}

//商品总数方法
$scope.nums = function(){
var num = 0;
for(var i = 0;i<$scope.list.length;i++){
num += $scope.list[i].gnum;
}
return num;
}

//商品总价方法
$scope.prices = function(){
var price = 0;
for(var i = 0;i<$scope.list.length;i++){
price += $scope.list[i].gprice * $scope.list[i].gnum;
}
return price;
}

//
$scope.chan = function(index){
if($scope.list[index].gnum <= 0){
if(confirm("确定要删除此商品吗?")){
$scope.list.splice(index,1);
}else{
$scope.list[index].gnum = 1;
}
}
}

//定义一个变量
$scope.order = "";

})



</script>

<style>
.css1{
background: limegreen;
}
.css2{
background: hotpink;
}
</style>

</head>
<body ng-controller="myCrtl">

<center>
<input type="text" ng-model="name" placeholder="根据名称查询" style="border-radius:10px;background: yellow;margin-left: 200px;"/>
<table border="1" cellspacing="0" style="margin-top: 10px;">
<tr style="background: #ccc;" align="center">
<td>商品编号<button ng-click="order='gid'">∧</button></td>
<td>商品名称</td>
<td>商品数量</td>
<td>商品单价</td>
<td>价格小计 <button ng-click="order = '- gnum*gprice'">∨</button></td>
<td>操作</td>
</tr>
<tr align="center" ng-repeat="li in list|filter:name|orderBy:order" class="{{$even?'css1':'css2'}}">
<td>{{li.gid}}</td>
<td>{{li.gname}}</td>
<td><input type="number"  ng-change="chan($index)" ng-model="li.gnum"/></td>
<td>{{li.gprice}}</td>
<td ng-bind="li.gnum * li.gprice"></td>
<td><button style="padding-right: 20px;background: yellow;border-radius: 10px;" ng-click="remove($index)">移除</button></td>
</tr>
<tr align="center">
<td style="background: lawngreen;" colspan="2">商品总数 :<span ng-bind="nums()"></span></td>
<td></td>
<td style="background: lawngreen;" colspan="2">商品总价:<span ng-bind="prices()"></span></td>
<td><button style="background: yellow;border-radius: 10px;" ng-click="removes()">清空购物车</button></td>
</tr>
</table>
</center>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值