我有一个包含 3 个复选框值的 html 文件
<input type="checkbox"ng-model="checkbox-1"/>
<input type="checkbox"ng-model="checkbox-2"/>
<input type="checkbox"ng-model="checkbox-3"/>
并且在 Controller 中定义了一个 watchCollection,当复选框状态改变时它会被触发
$scope.$watchGroup(['checkbox-1', 'checkbox-2', 'checkbox-3'], function (newValue, oldValue) {
console.log('checkbox-1: new - ' + newValue[0] + ' old - ' + oldValue[0]);
console.log('checkbox-1: new - ' + newValue[1] + ' old - ' + oldValue[1]);
console.log('checkbox-1: new - ' + newValue[2] + ' old - ' + oldValue[2]);
});
但是当 checkboc 值一次又一次地更新时,$watchCollection 的旧值列表没有正确更新,它会一直填充旧值。
例如
- 所有复选框最初都未勾选
- 勾选第一个复选框 -> oldValue = [false, false, false], newValue = [true, false, false]
- 现在勾选第二个复选框 -> oldvalue = [false, false, false], newValue = [true, true, false]
在旧值列表中,第一个值应该为 true,因为我们在第一个操作中将它更改为 true。但它仍然是最初的
我知道我可以通过使用模型值更新复选框变量并添加模型监视来解决此问题。如果有人有任何想法可以使用 $watchCollection 方法解决此问题,那就太好了?
JSFiddle - https://jsfiddle.net/a0h5nujo/
最佳答案
尝试添加这个:
$scope.$watchGroup(['checkbox-1', 'checkbox-2', 'checkbox-3'], function (newValue, oldValue) {
console.log('checkbox-1: new - ' + newValue[0] + ' old - ' + oldValue[0]);
console.log('checkbox-1: new - ' + newValue[1] + ' old - ' + oldValue[1]);
console.log('checkbox-1: new - ' + newValue[2] + ' old - ' + oldValue[2]);
},true);
",true)
如果您想深入了解它的工作原理,请阅读以下内容:
关于javascript - Angular $watchCollection 旧值未针对多次更新正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48135241/