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

通过angularjs添加表格数据实现增删总金额

2018-01-11 20:43 573 查看
<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../libs/angular.min.js"></script>
<style>
td,th{
width: 150px;
text-align: left;
}
table{
width: 800px;
border-collapse: collapse;
}
.num{
width: 70px;
text-align: center;
}
tr td:last-child button{
background-color: red;
}
#foot button{
background-color: red;
}
</style>
<script>
var app=angular.module('myapp',[]);
app.controller('vcl',function($scope){
$scope.product=[{
id:1000,
name:"鼠标",
quantity:1,
price:35
},{
id:1001,
name:"键盘",
quantity:2,
price:65
},{id:1002,name:"耳机",quantity:3,price:30},
{id:1003,name:"戴尔电脑",quantity:1,price:5500}
];
//减少数量
$scope.reduce=function(index){
if($scope.product[index].quantity>1){
$scope.product[index].quantity--;
}else{
$scope.remove(index);
}
}
//添加数量函数
$scope.add=function(index){
$scope.product[index].quantity++;
}
//所有商品总价函数
$scope.totalQuantity=function(){
var allprice=0;
for (var i=0;i<$scope.product.length;i++) {
allprice+=$scope.product[i].quantity*$scope.product[i].price;
}
return allprice;
}
//购买总数量函数
$scope.numAll=function(){
var numAlls=0;
for (var i=0;i<$scope.product.length;i++) {
numAlls+=$scope.product[i].quantity;
}
return numAlls;
}
//删除当前商品
$scope.remove=function(index){
if(confirm("确定要清空数据吗")){
$scope.product.splice(index,1)
}
}
//清空购物车
$scope.removeAll=function(){
if(confirm("你确定要清空购物车所有商品吗?")){
$scope.product=[];
}
}
//解决输入框输入负数时变为1
$scope.change=function(index){
if($scope.product[index].quantity>=1){

}else{
$scope.product[index].quantity=1;
}
}
$scope.$watch("product",function(oldvalue,newvalue){
console.log(oldvalue);
console.log(newvalue);
})
})
</script>
</head>
<body ng-app="myapp">
<div ng-controller="vcl">
<table border="" cellpadding="" cellspacing="">
<tr>
<th>产品编号</th>
<th>产品名称</th>
<th>购买数量</th>
<th>产品单价</th>
<th>产品总价</th>
<th>操作</th>
</tr>
<tr ng-repeat="x in product">
<td>{{x.id}}</td>
<td>{{x.name}}</td>
<td>
<button ng-click="reduce($index)">-</button>
<input type="text" class="num" ng-model="x.quantity" ng-change="change($index)" />
<button ng-click="add($index)">+</button></td>
<td>{{x.price}}</td>
<td>{{x.price*x.quantity}}</td>
<td><button ng-click="remove($index)">移除</button></td>
</tr>
</table>
<div id="foot"><span>总价:</span>
<span ng-bind="totalQuantity()"></span>
<span>购买数量</span>
<span>{{numAll()}}</span>
<button ng-click="removeAll()">清空购物车</button>
</div>
</div>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐