user2633328
user2633328

Reputation: 57

Confusion about first parameter of $scope.$watch

From the hitch hiker's guide to directive, light bulb example,

  scope.$watch(function() {
            scope.bulb = controller.getState();
        });

First parameter of $watch is a function, what is exactly being watched here?

I read another SO's post on scope, this is the explanation.

"The first parameter of the $watch method (the "watchExpression") can be either an Angular string expression (that is evaluated against the $scope), or a function, which is called with $scope as the first parameter."

I am still not clear about the use of function as a first parameter to $watch, from light bulb example - is scope implicitly passed as a parameter to that function? - does that function implicitly return scope.bulb, so scope.bulb is being watched?

Upvotes: 2

Views: 1939

Answers (3)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

This is an idiom to be notified whenever $digest is called. From the documentation, see the doc for $watch:

If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)

Upvotes: 0

Dennis
Dennis

Reputation: 14455

To me, this looks like a wrong usage of $watch. The function should return a value, which would be watched for changes, but in this case, it will always be undefined, so a change of the value will never be watched. A better approach would be something like this:

scope.$watch(function() {
    return controller.getState();
}, function(newVal) {
    scope.bulb = newVal;
});

This would watch for changes of controller.getState(), and would assign the new value to scope.bulb whenever it changes.

Upvotes: 0

Steve Klösters
Steve Klösters

Reputation: 9457

No, the function is being watched. This means the function is called and its value checked against the value it returned last time at least once every apply-digest cycle! The scope is indeed passed, but not used in your example. HTH

P.S. It is a bit odd to use a watch expression to set a value on the scope. What the watch expression function should do is return the state and set the scope value in the callback. That means it is only set when it changes rather than every time it is checked. Odd example!

Upvotes: 4

Related Questions