$watch
( type in module ng
)
Registers a listener callback to be executed whenever the watchExpression changes.
watchExpression is called on every call to $digest() and
should return the value which will be watched. (Since $digest()
reruns when it detects changes the watchExpression can execute multiple times per
$digest() and should be idempotent.)listener is called only when the value from the current watchExpression and the
previous call to watchExpression are not equal (with the exception of the initial run,
see below). The inequality is determined according to
angular.equals function. To save the value of the object for later comparison, the
angular.copy function is used. It also means that watching complex options will
have adverse memory and performance implications.listener may change the model, which may trigger other listener s to fire. This
is achieved by rerunning the watchers until no changes are detected. The rerun iteration
limit is 10 to prevent an infinite loop deadlock.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.)
After a watcher is registered with the scope, the listener fn is called asynchronously
(via $evalAsync) to initialize the
watcher. In rare cases, this is undesirable because the listener is called when the result
of watchExpression didn't change. To detect this scenario within the listener fn, you
can compare the newVal and oldVal . If these two values are identical ( === ) then the
listener was called due to initialization.
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
Scope#$watch(watchExpression[, listener][, objectEquality]);
watchExpression – {(function()|string)} –
Expression that is evaluated on each
$digest cycle. A change in the return value triggers a
call to the listener .
string : Evaluated as expressionfunction(scope) : called with current scope as a parameter.listener(optional) – {(function()|string)=} –
Callback called whenever the return value of
the watchExpression changes.
string : Evaluated as expressionfunction(newValue, oldValue, scope) : called with current and previous values as parameters.objectEquality(optional) – {boolean=} –
Compare object for equality rather than for reference.
{function()}
– Returns a deregistration function for this listener.