<html lang="en"> <head> <meta charset="UTF-8"> <title>日考13--Angular实现购物车</title> <script src="angular1.4.6.min.js"></script> <script src="jquery-3.2.1.js"></script> <script> var app=angular.module('myApp',[]); app.controller('myController',function($scope){ $scope.shopList=[ { name:'牛奶',price:'80.00',num:1}, { name:'墨水',price:'20.00',num:1}, { name:'牛肉面',price:'46.00',num:1}, { name:'袋鼠肉',price:'231.00',num:1}, { name:'海豹',price:'279.00',num:1} ]; //减少 $scope.reduce= function (index) { if($scope.shopList[index].num>1){ $scope.shopList[index].num--; }else{ $scope.remove(index); } }; //增加 $scope.add=function(index){ $scope.shopList[index].num++; }; //计算总价 $scope.allSum=function(){ var allPrice = 0; for(var i= 0;i<$scope.shopList.length;i++){ allPrice+=$scope.shopList[i].price*$scope.shopList[i].num; } return allPrice; }; //计算总数量 $scope.allNum=function(){ var allShu=0; for(var i=0;i<$scope.shopList.length;i++){ allShu+=Number($scope.shopList[i].num); } return allShu; }; //移除一项 $scope.remove=function(index){ if(confirm('确定移除此项吗?')){ $scope.shopList.splice(index,1); } }; //使得输入框中不得小于等于0 $scope.change=function(index){ if($scope.shopList[index].num>=1){ }else{ $scope.shopList[index].num=1; } }; //清空购物车 $scope.removeAll=function(){ if(confirm('确定清空购物车')){ $scope.shopList=[]; } } }); </script> </head> <body ng-app="myApp" ng-controller="myController"> <div class="container"> <ul class="list-group" > <li ng-repeat="shop in shopList" class="list-group-item"> <span>{{shop.name}}</span> <span>{{shop.price|currency}}</span> <span> <button ng-click="reduce($index)">-</button> <input type="text" ng-model="shop.num" ng-change="change($index)"> <button ng-click="add($index)">+</button> </span> <span>RMB ¥:{{shop.price*shop.num}}</span> <button class="btn btn-primary btn-xs" ng-click="remove($index)">移除</button> </li> </ul> 总价RMB ¥:<span ng-bind="allSum()"></span> 总数:<span ng-bind="allNum()"></span> <button class="btn btn-warning "ng-click="removeAll()">清空购物车</button> </div> </div> </body> </html>
angularJS实现购物车,可计价和计数
最新推荐文章于 2018-05-31 19:51:12 发布