あなたの問題に対するこの解決策を思いついた後、私はいたるところで笑っています. このソリューションは、個々のオブジェクトを監視するだけでなく、合計のために残りのオブジェクトを完全にループすることもありません。
http://plnkr.co/edit/oPWobcLLtJlxs5vjTYyc?p=preview
app.controller('MainCtrl', function($scope) {
$scope.stuff = STUFF;
var i;
$scope.sumOfSomething = 0;
$scope.sumOfSomethingElse = 0;
for(i=0;i < $scope.stuff.length;i++ ){
$scope.$watch('stuff['+i+'].something', function (newVal,oldVal) {
// happens when the watch is registered.
if(oldVal === newVal){
$scope.sumOfSomething += +newVal;
return;
}
if(newVal){
$scope.sumOfSomething += + (newVal - oldVal);
}
});
$scope.$watch('stuff['+i+'].somethingelse', function (newVal,oldVal) {
// happens when the watch is registered.
if(oldVal === newVal){
$scope.sumOfSomethingElse += +newVal;
return;
}
if(newVal){
$scope.sumOfSomethingElse += + (newVal - oldVal);
}
});
}
});
ちなみに、 に多数のオブジェクトがある場合、このソリューションがどの程度最適になるかはわかりませんSTUFF
。また、オブジェクトの数がSTUFF
変更される場合、これはそのままでは機能しません。基本的に行っていることは、angular のダーティ チェック ループを使用して合計を行うことです。
また、ウォッチ リスナーでの newVal と oldVal の順序にも注目してください。あなたの注文は間違っています。