1 回答
TA贡献1828条经验 获得超3个赞
使用当前图书价格进行初始化$scope.totalPrice(不需要它是一个函数),然后使用addBook和removeBook函数来更新$scope.totalPrice。
编辑:
由于$scope.totalPrice会受到多方面的影响,不仅是添加和删除书籍,还会更改书籍的数量和价格,因此需要在多个地方执行更新代码。像这样:
function CartControler($scope) {
$scope.books = [
{title: 'Absolute Java',
qty: 1, price: 114.95},
{title: 'Pro HTML5',
qty: 1, price: 27.95},
{title: 'Head First HTML5',
qty: 1, price: 27.89}
];
$scope.addBook = function (index) {
const newBook = {title: 'New Book', qty: 1, price: 10.99};
$scope.books.push(newBook);
$scope.totalPrice += newBook.price * newBook.qty;
}
$scope.removeBook = function(index) {
const bookToRemove = $scope.books[index];
$scope.books.splice(index, 1);
$scope.totalPrice -= bookToRemove.price * bookToRemove.qty;
}
$scope.updateTotal = function() {
$scope.totalPrice = 0;
for (i=0; i < $scope.books.length; i++) {
$scope.totalPrice += ($scope.books[i].price * $scope.books[i].qty);
}
}
$scope.updateTotal()
}
<!doctype html>
<html ng-app>
<head>
<title>Book Shopping Cart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.7/angular.min.js"></script>
<link rel="stylesheet" href="css/ex05.css">
</head>
<body ng-controller="CartControler">
<table>
<caption><b>My Books</b></caption>
<thead>
<tr>
<th>Title</th>
<th>Qty</th>
<th>UnitPrice</th>
<th>Line Total</th>
<th>Total {{totalPrice | currency}}</th> <!--I would like to display overall total here-->
</tr>
</thead>
<tbody >
<tr ng-repeat="book in books">
<td><input ng-model="book.title"></td>
<td>
<input ng-model="book.qty" size="2" ng-change="updateTotal()">
</td>
<td>
<input ng-model="book.price" ng-change="updateTotal()">
</td>
<td>{{book.price * book.qty | currency}}</td>
<td>
<button ng-click="removeBook($index)">
Remove
</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>
<button ng-click="addBook($index)">New</button>
</th>
<th></th>
<th></th>
<th>
<button ng-click="">Save</button>
</th>
<th></th>
</tr>
</tfoot>
</table>
</body>
</html>
添加回答
举报
