0
我試圖在向表格中添加項目時總計所有價格和數量。我無法讓總數刷新。有人可以在我的代碼中看到錯誤嗎?AngularJS不更新動態表格中的總數
$scope.updateTotals = [];
function ExampleCtrl ($scope){
$scope.people = [
{number: '1', title: 'Tom Sawyer', author: 'Mark Twain', price: '28', quantity: '2', action: 'xx'},
{number: '2', title: 'Alice\'s Adventure in Wonderland', author: 'Lewis Carroll', price: '17.00', quantity: '2', action: 'xx'},
{number: '3', title: 'The Old Man and the Sea', author: 'Ernest Hemingway', price: '17', quantity: '1', action: 'xx'}
];
$scope.addPerson = function(){
var person = {
number: $scope.number,
title: $scope.title,
author: $scope.author,
price: $scope.price,
quantity: $scope.quantity,
action: $scope.action
};
$scope.people.push(person);
};
$scope.removePerson = function (index){
$scope.people.splice(index, 1);
};
$scope.totPrice = function(){
var totPrice = 0;
var values = [$scope.people]
angular.forEach(values, function(price, quantity) {
totPrice += (price * quantity)
});
return totPrice;
};
$scope.totQty = function(){
var totQty = 0;
angular.forEach(
$scope.people.quantity, function (quantity){
totQty += (
$scope.people.quantity * $scope.people.title
);
return totQty; }
);
};
}
您可以使用['$ watchGroup'](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchGroup)來監控所有數量,並在其中一個數量時更新總數變化。 (順便說一下,使用一個名爲'people'和'person'的變量來引用產品是相當混亂的。) – Blazemonger 2014-09-23 15:18:22
爲什麼在迭代時要做'$ scope.people.quantity * $ scope.people.title' '$ scope.people.quantity'?你正試圖對數組或對象進行數學運算? – gonzofish 2014-09-23 15:21:56