Javascript 获取触发$watch的对象属性
使用$watch方法时(值相等)。是否有办法查看哪个对象属性已更改 e、 g 变成,Javascript 获取触发$watch的对象属性,javascript,angularjs,Javascript,Angularjs,使用$watch方法时(值相等)。是否有办法查看哪个对象属性已更改 e、 g 变成, $scope.$watch('buttons', function(newValue, oldValue) { if(newValue != oldValue && newValue !== undefined) { //Is there a way to know which button triggered thi
$scope.$watch('buttons', function(newValue, oldValue) {
if(newValue != oldValue && newValue !== undefined) {
//Is there a way to know which button triggered this watch?
}
}, true);
这是一个例子
我还希望看到一个角度内置功能,但现在您需要手动执行该操作
我将按钮放在对象数组中而不是散列键中,因为:
- 哈希键更难迭代和转换李>
- 我使用的是ng型号
嗯,您有
newValue
和oldValue
,所以您必须自己进行比较(if(newValue.booked!==oldValue.booked){booked changed!'
)。
$scope.$watch('buttons', function(newValue, oldValue) {
if(newValue != oldValue && newValue !== undefined) {
//Is there a way to know which button triggered this watch?
}
}, true);
$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);