2016-04-14 54 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

謝謝你,我會嘗試過 –