AngularJS未更新动态表中的总计
当我将一个项目添加到我的表中时,我试图合计所有价格和数量。我无法刷新总数。有人能看到我代码中的错误吗AngularJS未更新动态表中的总计,angularjs,dynamic,Angularjs,Dynamic,当我将一个项目添加到我的表中时,我试图合计所有价格和数量。我无法刷新总数。有人能看到我代码中的错误吗 $scope.updateTotals = []; function ExampleCtrl ($scope){ $scope.people = [ {number: '1', title: 'Tom Sawyer', author: 'Mark Twain', price: '28', quantity: '2', action: 'xx'}, {num
$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; }
);
};
}
如果我理解正确,totPrice计算总价格,并且addPerson作为ng click事件从HTML脚本中调用 您是否已尝试执行:
$scope.$apply();
说你有零钱
如何在HTML中显示“总价”
更好的方差是:
$scope.totPrice = function (){
var totPrice = 0;
var values = [$scope.people]
angular.forEach(values, function(price, quantity) {
totPrice += (price * quantity)
});
$scope.totalPrice = totPrice;
};
<span ng-bind="totalPrice">
$scope.totPrice=函数(){
var-totPrice=0;
var值=[$scope.people]
角度.forEach(值、函数(价格、数量){
总价+=(价格*数量)
});
$scope.totalPrice=总价;
};
而是将总价存储在变量中并进行绑定。您可以使用它监视所有数量,并在其中一个数量发生变化时更新总价。(顺便提一下,使用名为
people
和person
的变量来指代产品是相当令人困惑的。)为什么在迭代$scope.people.quantity*$scope.people.title
时要执行$scope.people.quantity
?你想对数组或对象进行数学运算?
$scope.totPrice = function (){
var totPrice = 0;
var values = [$scope.people]
angular.forEach(values, function(price, quantity) {
totPrice += (price * quantity)
});
$scope.totalPrice = totPrice;
};
<span ng-bind="totalPrice">