標籤:
1 <body ng-app> 2 3 <div class="container" ng-controller="carController"> 4 <table class="table" ng-show="cart.length"> 5 <thead> 6 <tr> 7 <th>產品編號</th> 8 <th>產品名字</th> 9 <th>購買數量</th>10 <th>產品單價</th>11 <th>產品總價</th>12 <th>操作</th>13 </tr>14 15 </thead>16 <tbody>17 <tr ng-repeat="item in cart">18 <td>{{item.id}}</td>19 <td>{{item.name}}</td>20 <td>21 <button type="button" ng-click="reduce(item.id)" class="btn btn-primary">-</button>22 <input type="text" value=" {{item.quantity}}" ng-model="item.quantity"/>23 <button type="button" ng-click="add(item.id)" class="btn btn-primary">+</button>24 </td>25 <td>{{item.price}}</td>26 <td>{{item.price * item.quantity}}</td>27 <td>28 <button type="button" ng-click="remove(item.id)" class="btn btn-primary">移除</button>29 </td>30 </tr>31 <tr>32 33 <td>總購買價</td>34 <td>{{totalPrice()}}</td>35 <td>總購買數</td>36 <td>{{totalQuantity()}}</td>37 <td colspan="2">38 <button type="button" ng-click="clearAll()" class="btn btn-primary">清空購購物車</button>39 </td>40 41 </tr>42 </tbody>43 </table>44 <p ng-show="!cart.length">你的購物車為空白</p>45 </div>46 47 </body>
1 /** 2 * Created by bh on 2016/4/24. 3 */ 4 var carController = function($scope){ 5 $scope.cart = [ 6 { 7 id:1000, 8 name:"iphone5s", 9 quantity:3, 10 price:4300 11 }, 12 { 13 id:3300, 14 name:"iphone5", 15 quantity:30, 16 price:3300 17 }, 18 { 19 id:232, 20 name:"mac", 21 quantity:3, 22 price:23000 23 }, 24 { 25 id:1400, 26 name:"ipad", 27 quantity:5, 28 price:6900 29 } 30 ]; 31 32 //計算總價 33 $scope.totalPrice= function(){ 34 var total = 0; 35 angular.forEach($scope.cart,function(item){ 36 total +=item.quantity * item.price; 37 }) 38 return total; 39 } 40 //計算總價 41 $scope.totalQuantity= function(){ 42 var total = 0; 43 angular.forEach($scope.cart,function(item){ 44 total +=parseInt(item.quantity); 45 }) 46 return total; 47 } 48 var findIndex =function(id){ 49 var index = -1; 50 angular.forEach($scope.cart,function(item,key){ 51 if(item.id === id){ 52 index = key; 53 54 } 55 }); 56 return index; 57 } 58 $scope.add=function(id){ 59 var index = findIndex(id); 60 if(index!== -1){ 61 ++$scope.cart[index].quantity; 62 } 63 } 64 $scope.reduce=function(id){ 65 var index = findIndex(id); 66 if(index!== -1){ 67 var item = $scope.cart[index]; 68 if(item.quantity > 1){ 69 --item.quantity; 70 }else{ 71 var returnKey = confirm("是否從購物車內刪除該商品"); 72 if(returnKey){ 73 $scope.remove(id) 74 } 75 } 76 77 } 78 } 79 80 //移除 81 $scope.remove=function(id){ 82 var index = findIndex(id) 83 84 if (index !== -1) { 85 $scope.cart.splice(index, 1) 86 } 87 } 88 $scope.$watch("cart",function(newValue,oldValue){ 89 angular.forEach(newValue,function(item,key){ 90 if(item.quantity < 1){ 91 var returnKey = confirm("是否從購物車內刪除該商品"); 92 if(returnKey){ 93 $scope.remove(item.id) 94 }else{ 95 item.quantity = oldValue[key].quantity 96 } 97 } 98 }) 99 })100 101 $scope.clearAll=function(){102 $scope.cart = {}103 }104 105 106 }
angular購物車