观察变量并进行更改

Viv*_*ndi 22 watch angularjs

在AngularJS中,我有一个监视范围变量的指令.当变量包含某些数据时,我需要稍微更改该变量.问题是,当我更改变量时,我$watch再次被触发.所以我最终处于一个连续的循环中.

scope.$watch('someVar', function(newValue, oldValue) {
    console.log(newValue);
    scope.someVar = [Do something with someVar];
});
Run Code Online (Sandbox Code Playgroud)

这会$watch再次触发,这是有道理的.但我确实需要一种方法来改变观察变量.有没有办法做到这一点?

pix*_*its 26

当使用变量监视变量时$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);

});
Run Code Online (Sandbox Code Playgroud)

注意:此技巧仅适用于对象引用.它不适用于原语.

通常,$watched在自己的$watch侦听器中更新变量不是一个好主意.但是,有时它可能是不可避免的.


cha*_*ndu 14

内部功能使用 如果条件要避免继续循环

scope.$watch('someVar', function(newValue, oldValue) {
   if(newValue!==oldValue) {
    console.log(newValue);
    scope.someVar = [Do something with someVar];
   } 
});
Run Code Online (Sandbox Code Playgroud)