Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - $观看一个物体($watch an object)

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');
    });
}

Here is fiddle .

(这是小提琴 。)

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

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

What is the correct way to do it?

(这样做的正确方法是什么?)

  ask by Vladimir Sidorenko translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Call $watch with true as the third argument:

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

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

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.

(默认情况下,在比较JavaScript中的两个复杂对象时,将检查它们是否为“引用”相等,它会询问两个对象是否引用相同的东西,而不是“值”相等,它会检查这些属性的所有属性的值对象是平等的。)

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

(根据Angular文档 ,第三个参数是objectEquality :)

When objectEquality == true , inequality of the watchExpression is determined according to the angular.equals function.

(当objectEquality == trueobjectEquality == true不等式根据angular.equals函数确定。)

To save the value of the object for later comparison, the angular.copy function is used.

(要保存对象的值以供以后比较,请使用angular.copy函数。)

This therefore means that watching complex objects will have adverse memory and performance implications.

(因此,这意味着观看复杂对象将产生不利的记忆和性能影响。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...