更新时间:2023-02-26 18:48:05
使用$scope.$watch
监视变量的更改时,角度检查引用是否已更改.如果具有,则执行$watch
处理程序以更新视图.
When a variable is watched for changes using $scope.$watch
, angular checks if the reference has changed. If it has, then the $watch
handler is executed to update the view.
如果您打算在$ watch处理程序中更改范围变量,它将触发一个无限的$ digest循环,因为范围变量引用在每次调用时都会更改.
If you plan on changing the scope variable within the $watch handler, it will trigger an infinite $digest loop because the scope variable reference changes every time that it is called.
解决无限摘要问题的技巧是使用 angular.copy (文档):
The trick to getting around the infinite digest issue is to preserve the reference inside your $watch
handler using angular.copy (docs):
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);
});
注意:此技巧仅适用于对象引用.它不适用于原语.
Note: This trick only works for object references. It will not work with primitives.
通常,在自己的$watch
侦听器中更新$watched
变量不是一个好主意.但是,有时这是不可避免的.
In general, its not a good idea to update a $watched
variable within its own $watch
listener. However, sometimes it may be unavoidable.