观看变量并进行更改 [英] Watch variable and change it
问题描述
在AngularJS中,我有一个指令来监视作用域变量.当变量包含某些数据时,我需要对该变量进行一些更改.问题是,当我更改变量时,再次触发$watch
.所以我最终陷入了连续循环.
In AngularJS I have a directive that watches a scope variable. When the variable contains certain data then I need to alter that variable a bit. The problem is that when I change the variable that my $watch
is triggered again. So I end up in a continuous loop.
scope.$watch('someVar', function(newValue, oldValue) {
console.log(newValue);
scope.someVar = [Do something with someVar];
});
这将继续触发$watch
,这很有意义.但是我确实需要一种更改监视变量的方法.有办法吗?
This keeps triggering $watch
again, which makes sense. But I do need a way to change the watched variable. Is there a way to do this?
推荐答案
使用$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.
这篇关于观看变量并进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!