$watch 一个对象 [英] $watch an object

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

问题描述

我想观察字典中的变化,但由于某种原因没有调用观察回调.

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

这是我使用的控制器:

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

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

这是fiddle.

我希望每次更改名称或姓氏时都会触发 $watch 回调,但它不会发生.

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

正确的做法是什么?

推荐答案

使用 true 作为第三个参数调用 $watch:

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.

根据 Angular 文档,第三个参数用于 objectEquality:

Per the Angular documentation, the third parameter is for objectEquality:

objectEquality == true时,watchExpression的不等式根据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.

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

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