<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/angular.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.Product = [{
id: 1000,
name: "iphone8",
quantity: 1,
price: 8888
}, {
id: 1001,
name: "iPhone9",
quantity: 1,
price: 9888
}, {
id: 1002,
name: "iPhone 2s",
quantity: 1,
price: 3888
}, {
id: 1003,
name: "iPhone 7P+",
quantity: 1,
price: 10088
}]
//减少数量
$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="myCtrl">
<table border="" cellspacing="" cellpadding="">
<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>
</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>
网友评论