解浩佳购物车

来源:互联网 发布:极度干燥 知乎 编辑:程序博客网 时间:2024/09/21 08:19
<!DOCTYPE html>
<html>


<head>
<meta charset="UTF-8">
<title></title>
<script src="js/angular.min.js"></script>
<style type="text/css">
td,
th {
width: 150px;
text-align: center;
}

table {
width: 800px;
}

.num {
width: 50px;
text-align: center;
}

.bt {
margin-left: 715px;
background-color: red;
}

.bt2 {
background-color:blue;
}
</style>
</head>
<!--
    作者:解浩佳
    时间:2017-09-22
    描述:使用angular构造一个购物车
    -->
<!--ng-bind是从$scope -> view的单向绑定ng-modle是$scope <-> view的双向绑定{{}} 与 ng-bind 的区别是后者在加载时用户不会看到渲染之前的东西,前者可能会看到,所以首页一般用后者加载数据-->


<body ng-app="myApp">
<h1>我的购物车</h1>
<div ng-controller="VC1">
<button class="bt" ng-click="removeAll()">清空购物车</button>
<table border="" cellspacing="" cellpadding="">
<tr>
<th><input type="checkbox"/></th>
<th>name</th>
<th>price</th>
<th>number</th>
<th>totalPrice</th>
<th>option</th>
</tr>
<tr ng-repeat="x in Product">
<th><input type="checkbox"/></th>
<td>{{x.name}}</td>
<td>{{x.price | currency:'¥' }}</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 * x.quantity | currency:'¥'}}</td>
<td><button class="bt2" ng-click="remove($index)">删除</button></td>
</tr>
</table>
<div id="foot"><span>总价:</span><span ng-bind="totalQuantity()"></span><span>购买数量</span>
<span>{{numAll()}}</span>  </div>
</div>
</body>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("VC1", function($scope) {
$scope.Product = [{
name: "qq",
price: 12.90,
quantity: 1

}, {
name: "wx",
price: 23.90,
quantity: 1

}, {
name: "wx",
price: 99.90,
quantity: 1

}, {
name: "ll",
price: 99.90,
quantity: 1

}];
//减少数量
$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>


</html>
原创粉丝点击