diff options
| author | Wesley Cho | 2013-10-16 00:04:36 -0400 | 
|---|---|---|
| committer | Pete Bacon Darwin | 2013-10-24 23:13:30 +0100 | 
| commit | 459e85bfea421f46b978790924180b9a95e4ae78 (patch) | |
| tree | 1366ec64bad5e01a5ed7c76957faeda81c0c0874 | |
| parent | 1ae34aac811629df201c3d41d7976559cf7aaf5d (diff) | |
| download | angular.js-459e85bfea421f46b978790924180b9a95e4ae78.tar.bz2 | |
docs(rootScope): add example of using a listener function for $watch
Closes #4451
| -rw-r--r-- | src/ng/rootScope.js | 32 | 
1 files changed, 32 insertions, 0 deletions
| 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         * <pre> @@ -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);   +         * </pre>         *         * | 
