I'm trying to figure out how to watch an array and update an object, like this.
var vm = this; //controller
vm.order = {
totalValue: 25,
products: [{id:0, val: 10, qtd: 1}, {id:1, val: 15, qtd: 1}]
};
If I push a new product into this order object, how do I update the totalValue just watching the collection ? (totalValue = All Val * All Qtd)
It is necessary because the "qtd" field is bind to an input field, so I can change the value of all "products" at any time.
UPDATE
$scope.$watchCollection(
function() { return self.order.products; },
function(products) {
self.order.totalValue = products.reduce(function (p, n) {
console.log(n.qtd);
console.log(n.val);
return p + n.qtd * n.val;
}, 0);
});
The code worked, but only when I push a new "product" into order. I have to watch every order.products.product.qtd and change the order.totalValue every time the user change the qtd of a product