1. 程式人生 > >購物車實現清空小計總計

購物車實現清空小計總計

<!DOCTYPE html>
<html>


<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/angular.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
angular.module("myapp", []).controller("myctrl", function($scope, $http) {
$scope.flag = true;
//1.獲取資料
$http.get("http://result.eolinker.com/rR1VBtT56a6bb220c10b3d44b65b4787a8aec03c4ec32ce?uri=ThirdTest").then(function(cheng) {
$scope.goods = cheng.data;
//alert($scope.goods.length);
})
//2.總價
$scope.getTotal = function() {
var t = 0;
for(var i = 0; i < $scope.goods.length; i++) {
t = t + $scope.goods[i].number * $scope.goods[i].price;
}
return t;
}
//3.刪除---單行
$scope.del = function(i) {
$scope.goods.splice(i, 1);
}
//4.清空購物車
$scope.clear = function() {
$scope.goods = [];
$scope.flag = false;
}
//5.減少數量
$scope.jian = function(index) {
var num = $scope.goods[index].number;
if(num > 1) {
$scope.goods[index].number--;
} else {
var f = confirm("是否刪除此商品?");
if(f) {
$scope.goods.splice(index, 1);
}
}
}


})
</script>
</head>


<body ng-app="myapp" ng-controller="myctrl" style="width: 600px;">
<h2>我的購物車</h2>
<span ng-show="!flag">你的購物車已清空<a href="#">去商城逛逛</a></span>
<button ng-click="clear()" style="float: right;">清空購物車</button>
<table border="1px" cellspacing="0" cellpadding="0" width="600px" ng-show="flag">
<tr>
<td><input type="checkbox" ng-model="ischeck" /></td>
<td>商品名稱</td>
<td ng-click="px='-price'">商品價格</td>
<td>商品數量</td>
<td ng-click="px='number*price'">小計</td>
<td>操作</td>
</tr>
<tr ng-repeat="s in goods|orderBy:px">
<td><input type="checkbox"  ng-model="ischeck" /></td>
<td>{{s.name}}</td>
<td>{{s.price|currency:"¥"}}</td>
<td><button ng-click="s.number=s.number+1">+</button><input type="text" value="{{s.number}}" /><button ng-click="jian($index)">-</button></td>
<td>{{s.number*s.price|currency:"¥"}}</td>
<td><button ng-click="del($index)">刪除</button></td>
</tr>
</table>
<span ng-show="flag">總計:{{getTotal()|currency:"¥"}}</span>
</body>


</html>