0

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

1 Answer 1

1

Try this way:

$scope.$watch('order.products', function (products) {
    scope.order.totalValue = products.reduce(function (p, n) {
        return p + n.qtd * n.val;
    }, 0);
}, true);

This will deep watch array to detect qtd and val changes inside array items.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I have instead of "$scope.orders" I has "var vm = this; vm.orders" ? I've updated the question
Then you'll have to adjust your function accordingly like described here.
Thanks very much for the help @karaxuna

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.