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. The inequality is determined according to
angular.equals
function. To save the value of the object for later comparison
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 100 to prevent infinity loop deadlock.If you want to be notified whenever $digest
is called,
you can register an 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.)
var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(scope, newValue, oldValue) { counter = 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);
angular.scope.$watch(watchExpression[, listener]);
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(scope, newValue, oldValue)
: called with current scope
an previous and
current values as parameters.{function()}
– Returns a deregistration function for this listener.