且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

观看变量并进行更改

更新时间: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.