由于$watch()采用角度表达式,您可以使用自定义观察器函数。在您的情况下,观察更改的最简单方法是将所有您感兴趣的字段相加,然后返回一个对角度来说很好且有效的数字,并且您的总和将准备好呈现。
var sumThings = function(obj, field) {
var val = 0;
obj.forEach(function(o) {
val += parseInt(o[field]);
});
return val;
};
$scope.$watch(function() { return sumThings($scope.stuff, "something")}, function (newVal, oldVal) { //console.log("watchExpression('something') fired!", oldVal, newVal);
$scope.somethingSum = newVal;
});
$scope.$watch(function() { return sumThings($scope.stuff, "somethingelse")}, function (newVal, oldVal) {
$scope.somethingelseSum = newVal;
});
基本上,通过进行求和,您就是在进行自己的脏检查。$watch(STUFF, true)如果您的对象比您在此处显示的更复杂,它会更有效。