我需要对产品列表中的价格进行求和,并在产品添加到列表中时保持总和更新。总和数组的每个值
我使用的是服务,因为该项目将填补与他人阵列的对象。但在下面$scope.total
返回任何的代码:
阵列例如: $ scope.items = [{ ID:1,诺姆: “Nosso咖啡”,PRECO:5,如:69,quantidade:1,IMG: 'img/mais_1.jpg'} ];
.controller('pedidoCtrl', function($scope, produtoService) {
$scope.items = null;
$scope.items = produtoService.getProdutos();
$scope.deleteItem = function(item) {
$scope.items.splice($scope.items.indexOf(item), 1);
};
$scope.$watchCollection('items', function(array) {
var total = 0;
if (array) {
angular.forEach(array, function(index) {
total += array[index].preco;
});
}
$scope.total = total;
});
})
.service('produtoService', [function() {
var produtosLista = [];
var addProduto = function(produto) {
produtosLista.push(produto);
};
var getProdutos = function() {
return produtosLista;
};
return {
addProduto: addProduto,
getProdutos: getProdutos,
};
}]);
请看到新版本,即时通讯愚蠢的,我是改变了一些东西,我忘了备份 –
@FelipeCustódio请看到更新的答案。我错过了你的.forEach函数的不正确使用。请参阅文档:https://docs.angularjs.org/api/ng/function/angular.forEach forEach首先获取数组元素参数,然后获取索引(可选)。 – Strelok
谢谢,我会看到 –