What $watch method in angularjs really returns and how it works?

angularjs, function, javascript, watch

Solution

The code you've shown is in a nutshell

- storing reference to (just added) `$watch()` returned value (see below `$rootScope.$watch` returned value)

- once first time is that `$watch()` called, it calls that referenced `function` - which leads to ubinding of that `$watch()`

Read this nice article

Unbinding $watch() Listeners In AngularJS

a small extract from a summary:

As you can see, we're storing the function reference returned by the `$watch()` statement; then, once the `$watch()` fires a few times, we invoke that stored method, unbinding the $watch() listener.

In that example, there is an if statement, which could help us to decide, when is the best time to remove that `$watch()` (e.g. after the first evaluation) ...

The more detailed defintion of the `scope.$watch()` could be found here:

- $rootScope.Scope

And as we can see from this extract:

`$watch(watchExpression, [listener], [objectEquality]);`

... Returns a deregistration function for this listener.

Problem

I have difficulty understanding the following codes even with the comments ``` // Store the initial cell value so we can reset to it if need be var oldCellValue; var dereg = scope.$watch('ngModel', function() { oldCellValue = ngModel.$modelValue; dereg(); // only run this watch once, we don't want to overwrite our stored value when the input changes }); ``` How many time does function dereg got called in this case? Is this a recursion?

Original source