Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js watch only on particular object property

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..

like image 509
fxck Avatar asked Mar 20 '13 11:03

fxck


1 Answers

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

like image 136
Mathew Berg Avatar answered Sep 30 '22 04:09

Mathew Berg