2016-04-14 72 views
1

我需要对产品列表中的价格进行求和,并在产品添加到列表中时保持总和更新。总和数组的每个值

我使用的是服务,因为该项目将填补与他人阵列的对象。但在下面$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, 
    }; 
}]); 

回答

4

你不是说要你的产品总数添加到resultado变量?然后将其分配给$scope.total

$scope.$watchCollection('items', function(array) { 
    var total = 0; 
    if (array) { 
     angular.forEach(array, function(item) { 
      total += item.preco; 
     }); 
    } 
    $scope.total = resultado; 
}); 

,或者你可以做

$scope.$watchCollection('items', function(array) { 
    if (array) { 
     $scope.total = array.reduce(function(total,item) { 
      return total + item.preco; 
     },0); 
    } 
}); 
+0

请看到新版本,即时通讯愚蠢的,我是改变了一些东西,我忘了备份 –

+0

@FelipeCustódio请看到更新的答案。我错过了你的.forEach函数的不正确使用。请参阅文档:https://docs.angularjs.org/api/ng/function/angular.forEach forEach首先获取数组元素参数,然后获取索引(可选)。 – Strelok

+0

谢谢,我会看到 –

0

试试这个:

$scope.$watchCollection('items', function(array) { 
    var total = 0; 
    if (array) { 
     angular.forEach(array, function(value) { 
      total += value.preco; 
     }); 
    } 
    $scope.total = total; 
}); 
+0

对不起,我正在改变填充的东西之前,我忘了备份,但即使是固定犯规工作 –

+0

我更新的答案 –

+0

谢谢你,我会尝试过 –