当您使用$ watch方法时(按值相等)。有没有办法查看哪个对象属性已更改?
e.g。
/**
* Save state of button: Cancelled
*/
$scope.$watch('buttons.cancelled', function(newValue, oldValue) {
if(newValue != oldValue && newValue !== undefined) {
privates.viewState.buttons.cancelled = $scope.buttons.cancelled;
}
});
/**
* Save state of button: Booked
*/
$scope.$watch('buttons.booked', function(newValue, oldValue) {
if(newValue != oldValue && newValue !== undefined) {
privates.viewState.buttons.booked = $scope.buttons.booked;
}
});
变成了;
$scope.$watch('buttons', function(newValue, oldValue) {
if(newValue != oldValue && newValue !== undefined) {
//Is there a way to know which button triggered this watch?
}
}, true);
答案 0 :(得分:1)
这是example。
我还想看一个角度内置功能但是现在需要手动执行此功能
我将按钮放在对象数组中,而不是放在哈希键中,因为:
$scope.buttons = [
{ name: 'cancelled', checked: false},
{ name: 'booked', checked: false},
{ name: 'something', checked: false}
];
$scope.$watch('buttons',function(newVal,oldVal){
oldVal = oldVal.reduce(function(p,k){ p[k.name] = k.checked; return p;},{});
var changed = newVal.filter(function(k){
return oldVal[k.name] !== k.checked;
});
changed = changed.reduce(function(p,k){ p[k.name] = k.checked; return p;},{});
$scope.changed = changed;
},true);