Thierry Templier
Thierry Templier

Reputation: 202138

Model update detection

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

Upvotes: 0

Views: 156

Answers (1)

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

Yes it is expected behavior After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. You can add below line to function

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

Upvotes: 2

Related Questions