From 459e85bfea421f46b978790924180b9a95e4ae78 Mon Sep 17 00:00:00 2001 From: Wesley Cho Date: Wed, 16 Oct 2013 00:04:36 -0400 Subject: docs(rootScope): add example of using a listener function for $watch Closes #4451 --- src/ng/rootScope.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'src/ng/rootScope.js') diff --git a/src/ng/rootScope.js b/src/ng/rootScope.js index 58aedd05..8be495db 100644 --- a/src/ng/rootScope.js +++ b/src/ng/rootScope.js @@ -240,6 +240,8 @@ function $RootScopeProvider(){ * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * + * The example below contains an illustration of using a function as your $watch listener + * * * # Example *
@@ -261,6 +263,36 @@ function $RootScopeProvider(){
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
+
+
+
+ // Using a listener function
+ var food;
+ scope.foodCounter = 0;
+ expect(scope.foodCounter).toEqual(0);
+ scope.$watch(
+ // This is the listener function
+ function() { return food; },
+ // This is the change handler
+ function(newValue, oldValue) {
+ if ( newValue !== oldValue ) {
+ // Only increment the counter if the value changed
+ scope.foodCounter = scope.foodCounter + 1;
+ }
+ }
+ );
+ // No digest has been run so the counter will be zero
+ expect(scope.foodCounter).toEqual(0);
+
+ // Run the digest but since food has not changed cout will still be zero
+ scope.$digest();
+ expect(scope.foodCounter).toEqual(0);
+
+ // Update food and run digest. Now the counter will increment
+ food = 'cheeseburger';
+ scope.$digest();
+ expect(scope.foodCounter).toEqual(1);
+
*
*
*
--
cgit v1.2.3