Angular.js watch only on particular object property

fxck picture fxck · Mar 20, 2013 · Viewed 13.9k times · Source

Basically I want this http://plnkr.co/edit/3yfXbo1c0llO40HZ8WNP?p=preview but watch doesn't fire when I change something..

I know that this would have worked

$scope.$watch('stuff', function (newVal, oldVal) {
    console.log(oldVal, newVal);

}, true);

But since I want to do some summing up inside the watches and I don't want to unnecessarily loop thru or re-sum values that did not change..

//edit - note that the plnkr example is just an extraction from the actual app, where you can add and remove rows and much more, like modifying the total number(sum of somethings and somethingelses) from another input outside the ng-repeat..

Answer

Mathew Berg picture Mathew Berg · Mar 20, 2013

I would not do a watch as depending on how large your array could be, might be very taxing. Instead I would just create a filter:

HTML:

Sum of something is: {{ stuff | sum:'something' }}<br/>
Sum of somethingelse is: {{ stuff | sum:'somethingelse' }}

Javascript:

.filter("sum", function(){
    return function(input, params){
        var totalSum = 0;
        for(var x = 0; x < input.length; x++){
            totalSum += input[x][params];
        }
        return totalSum;
    }
})

plnkr: http://plnkr.co/edit/p6kM3ampSuMXnwqcteYd?p=preview