我正在编写一个应用程序,它允许您添加和删除书籍。它计算每行图书的总价值。我正在尝试将 $scope.books.price 中的所有价格相加,但我似乎无法理解如何编写 for 循环。
对象属性为:
- 标题:
- 数量:
- 价格:
我想显示对象数组中的总价格并将它们显示在表格标题总单元格中。
如何遍历对象以捕获价格并显示在标题上?
<!doctype html>
<html lang='en' 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>
<script>
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}
];
// need help with this portion can't seem to get the prices to print out
$scope.totalPrice = function() {
for (i=0; i < $scope.books.length; i++) {
$scope.totalPrice += $scope.books.price[i];
}
}
$scope.addBook = function (index) {
console.log("add new book");
$scope.books.push({title: 'New Book', qty: 1, price: 10.99});
}
$scope.removeBook = function(index) {
$scope.books.splice(index, 1);
}
}
</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">
</td>
<td>
<input ng-model="book.price" >
</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>