AngularJS:$看对象 [英] AngularJS : $watch an object

查看:115
本文介绍了AngularJS:$看对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty肯定,我失去了一些东西很简单,在这里。

I'm pretty sure i'm missing something very simple here.

我要观看在字典中的变化,但由于某种原因手表回调不叫。

I want to watch for changes in a dictionary, but for some reason watch callback is not called.

下面是我用一个控制器:

Here is a controller that I use:

function MyController($scope) {
    $scope.form = {
        name: 'my name',
        surname: 'surname'
    }

    $scope.$watch('form', function(newVal, oldVal){
        console.log('changed');
    });
}

下面是小提琴: http://jsfiddle.net/Y8ByG/

我希望$腕表回调被解雇每次的名字或姓氏更改,但它不会发生。

I expect $watch callback to be fired each time name or surname is changed, but it doesn't happen.

什么是做了正确的方法是什么?

What is the correct way to do it?

感谢您

推荐答案

呼叫 $观看真正作为第三个参数:

Call $watch with true as the third argument:

$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

在默认情况下比较JavaScript中两种复杂的对象时,它们将被检查是否参考平等,它要求如果两个对象指的是同样的事情,而不是价值的平等,它检查是否所有的值这些对象的属性是相同的。

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.

按照角文档,第三个参数是 objectEquality

objectEquality ==真中,watchEx pression的不平等根据的 angular.equals 功能。保存以供日​​后比较对象的值时, angular.copy 功能被使用。因此,这意味着,看复杂的物体会产生不良的内存和性能的影响。

When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

这篇关于AngularJS:$看对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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