<!DOCTYPE html><html lang="en" ng-app="app"><head> <meta charset="UTF-8"> <title>购物车</title> <link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.css"> <script src="../vendor/angular.js"></script> <script src="car-controller.js"></script></head><body> <div class="table-responsive container" ng-controller="CarCtrl"><table class="table " ng-show="data.length"> <thead> <tr><th>产品编号</th><th>产品名字</th><th>购买数量</th><th>产品单价</th><th>产品总价</th><th>操作</th></tr> </thead> <tr ng-repeat="value in data"><td>{{value.id}}</td><td>{{value.name}}</td><td> <button class="btn btn-primary" ng-click="reduce(value.id)" >-</button> <input type="number" name="num" ng-model="value.quantity" id="num"> <button class="btn btn-primary" ng-click="add(value.id)">+</button></td><td>{{value.price}}</td><td>{{value.price*value.quantity}}</td><td> <button class="btn btn-danger" ng-click="removeItem(value.id)">移除</button></td> </tr> <tfoot> <tr><td></td><td>总购买数量 </td><td>{{totalQuantity()}}</td><td>总购买价</td><td>{{totalPrice()}}</td><td> <button class="btn btn-danger" ng-click="data=null">清空购物车</button></td> </tr> </tfoot></table><p ng-show="!data.length">您的购物车为空</p> </div></body></html>2、js逻辑部分
var app=angular.module("app",[]); var carController=function($scope){$scope.data=[ {id:1,name:"HuaWei",quantity:"2",price:4300 }, {id:2,name:"iphone7",quantity:"3",price:6300 }, {id:3,name:"XiaoMi",quantity:"3",price:2800 }, {id:4,name:"Oppo",quantity:"3",price:2100 }, {id:5,name:"Vivo",quantity:"3",price:2100 }] }注意:
/* * 计算总价 * @method: angular.forEach() * @param: 1. $scope.obj:要遍历的scope上的数据 * 2. function(item){} 回调,在函数内部处理遍历的数据 * */$scope.totalPrice=function(){ var total=0; angular.forEach($scope.data,function(item){total+=item.quantity*item.price; }) return total} /*计算总数量*/$scope.totalQuantity=function(){ var total=0; angular.forEach($scope.data,function(item){total+=item.quantity; }) return total}说明:
/*移除某项* @param:传入当前项的id作为参数,以确定移除哪一项* */$scope.removeItem=function(id){ var index=findIndex(); $scope.data.splice(index,1);}说明:
/*查找当前操作的元素的位置*/function findIndex(id){ var index=-1; angular.forEach($scope.data,function(value,key,obj){if(value.id===id){ index=key; return index;} }) return index;}3.清空操作
<tr> <td></td> <td>总购买数量 </td> <td>{{totalQuantity()}}</td> <td>总购买价</td> <td>{{totalPrice()}}</td> <td><button class="btn btn-danger" ng-click="data=null">清空购物车</button> </td></tr>4. 增加和删除商品数量
/*增加商品数量*/$scope.add=function(id){ var index=findIndex($scope,id),item=$scope.data[index]; item.quantity++;}/*减少商品数量* @description:* 减少当前项的数量,当仅剩一件时弹出对话框确认是否清空。是则调用removeItem方法清除当前项* */$scope.reduce=function(id){ var index=findIndex($scope,id),item=$scope.data[index]; if(item.quantity>1){ //判断当前项是否还能再减item.quantity--; }else{var makesure=confirm("确定要清空当前项吗??");if(makesure){ $scope.removeItem(id)} }}总结:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。