我需要對產品列表中的價格進行求和,並在產品添加到列表中時保持總和更新。總和數組的每個值
我使用的是服務,因爲該項目將填補與他人陣列的對象。但在下面$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
謝謝,我會看到 –