0

I try to implement an autosaving feature for my forms basing on the $watch function of AngularJS. I initialized watching as described below:

var unbindWatcher = $scope.$watch('selectedElement', function(newValue, oldValue) {
    (...)
});

The selected element is loaded using the $resource object and its query method. The selectedElement is set then using one element of the list. Fields of the selectedElement are linked with form elements using ng-model attribute.

The problem is that the callback specified in the $watch method is called once before any update is done.

Is it a normal behavior of the $watch method? How to catch when the selectedElement is actually updated?

Thanks for your help. Thierry

4

1 回答 1

2

是的,这是预期的行为在观察者注册到作用域后,监听器 fn 被异步调用(通过 $evalAsync)来初始化观察者。您可以将以下行添加到功能

var unbindWatcher = $scope.$watch('selectedElement', function(newValue, oldValue) {
    if(newvalue===oldvalue) return;
});
于 2013-06-28T20:06:11.160 回答