观察变量并改变它 [英] Watch variable and change it

查看:35
本文介绍了观察变量并改变它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 监视变量的变化时,angular 会检查引用是否发生了变化.如果是,则执行 $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保留$watch 处理程序中的引用(文档):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆