当使用监视变量的变化时
$scope.$watch,角度检查参考值是否已更改。如果具有,则
$watch执行处理程序以更新视图。
如果您打算在$ watch处理程序中更改范围变量,它将触发一个无限的$ digest循环,因为范围变量引用在每次调用时都会更改。
解决无限摘要问题的技巧是使用 angular.copy
(docs)在处理程序中
保留 引用:
$watch
__
scope.$watch('someVar', function(newValue, oldValue) { console.log(newValue); var someVar = [Do something with someVar]; // angular copy will preserve the reference of $scope.someVar // so it will not trigger another digest angular.copy(someVar, $scope.someVar);});注意:此技巧仅适用于对象引用。它不适用于原语。
通常,
$watched在其自己的
$watch侦听器中更新变量不是一个好主意。但是,有时这是不可避免的。



