AngularJS小案例_购物车

本文介绍了一种利用Angular框架来实现购物车功能的方法。通过定义一个包含商品名称、价格等属性的产品数组,并借助Angular内置的指令实现了商品数量的增减及总价的实时更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>shopcart.</title>
    
<!--  首先引入angular的插件-->
<script type="text/javascript" src="js/angular.min.js"></script>
  
  <script type="text/javascript">
var app = angular.module("app",[]);
app.controller("AppController",["$scope",function($scope){
//定义一个数组
$scope.productList = [{name:"鼠标",price:50,num:1,myTotal:50}
,{name:"书包",price:150,num:1,myTotal:150}
,{name:"笔记本",price:5000,num:1,myTotal:5000}
];


$scope.total=function(){
//总数量
$scope.totalNum = 0;
//总价格
$scope.totalPrice = 0;
for(var i=0; i<$scope.productList.length; i++){
var product = $scope.productList[i];
$scope.totalNum += product.num;
$scope.totalPrice += product.num*product.price;
}
};
$scope.total();

 //数量-1
$scope.del=function(index){
$scope.productList[index].num--;
$scope.total();
};
//数量+1
$scope.add=function(index){
$scope.productList[index].num++;
$scope.total();
};


  }]);
  </script>
  </head>
  
 <body  ng-app="app" ng-controller="AppController">
<h1>购物车</h1>
<table border="1" style="background-color: brown">
<tr>
<td>商品名称</td>
<td>商品单价</td>
<td>商品数量</td>
<td>商品总价</td>
</tr>
   <tr  ng-repeat="p in productList">
        <td>{{ p.name}}</td>
        <td>{{p.price}}</td>
        <td>
<button ng-click="del($index)">-</button>
<input type="text"  ng-model="p.num"/>
      <button ng-click="add($index)">+</button>
</td>
<td>{{p.price*p.num}}</td>
   </tr>
   <tr >
        <td colspan="2"></td>
        <td>{{totalNum}}</td>
        <td>{{totalPrice}}</td>
   </tr>
      </table>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值