使用AngularJS观看整个对象(深入观察) [英] Watch entire object (deep watch) with AngularJS

查看:58
本文介绍了使用AngularJS观看整个对象(深入观察)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是表示表单数据的作用域angular-resource variable / object:

This is a scope angular-resource variable / object that represents a form data:

    $scope.form = {
              name: 'bob', 
              email: 'bob@bobs.com'
    }

有一种方法可以观察到我的name变量发生了变化.

There is the way I watch where my name variable is changed.

    $scope.$watch('form.name', function(newVal) {
        if(newVal) {
            alert(newVal)
        }
    });

如何查看文件名是否更改(电子邮件,名称或电子邮件,scope.form可能具有的内容)?

What would be a way to watch if any of fileds was changed- name, email, or whatever scope.form may have?

我的目的是根据用户更改表单上的某些事实来禁用或启用我的表单保存".

My purpose to make my form 'save' disabled or enabled depending on that fact that user has changed something on the form.

推荐答案

$watch()的第三个参数将使它检查对象的相等性(深入监视).

There is a third parameter of $watch() that will make it check for object equality (deep watch).

  $scope.$watch('form', function(newVal) { //watch the whole object
        if(newVal) {
            alert(newVal);
        }
    }, true); //pass "true" here.

为进一步完善我的答案,在这种情况下,这两种方法都会产生相同的结果:此处为在线演示(点击).,但 $watchCollection很浅,不会监视嵌套的任何更改.

To further complete my answer, both of these approaches produce the same result in this case: Live demo here (click). but $watchCollection is shallow and will not watch anything nested for changes.

  $scope.$watch('form', function(newForm, oldForm) {
    console.log(newForm.name);
  }, true);

OR:(不是深入了解)

  $scope.$watchCollection('form', function(newForm, oldForm) {
    console.log(newForm.name); 
  });

这篇关于使用AngularJS观看整个对象(深入观察)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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