gpt4 book ai didi

javascript - 获取触发 $watch 的对象属性

转载 作者:行者123 更新时间:2023-11-29 15:39:53 25 4
gpt4 key购买 nike

当您使用 $watch 方法时(按值相等)。有没有办法查看更改了哪个对象属性?

例如

/**
* 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);

最佳答案

这是一个 example .

我也希望看到一个 Angular 内置功能,但就目前而言,您需要手动执行此操作

我将按钮放在对象数组 中而不是散列键中,因为:

$watch 是用新值旧值调用的,只需比较它们:

$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);

关于javascript - 获取触发 $watch 的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21116278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com