AngularJS小案例_購物車




<%@ 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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章