Chapter 7: Creating a universal watch callback

by billy roberts

HTML

<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="Ctrl">
        <input ng-model="foo" />
        <input ng-model="bar" />
    </div>
</div>

JavaScript

angular.module('myApp', [])
.controller('Ctrl', function($scope, $log) {
    // invoked once every time $scope.foo is modified
    $scope.$watch('foo', function(newVal, oldVal, scope) {
        // newVal is the current value of $scope.foo
        // oldVal isa the previous value of $scope.foo
        // scope === $scope
        $log.log('foo watcher', newVal, oldVal, scope);
    });
    
    // invoked once every time $scope.bar is modified
    $scope.$watch('bar', function(newVal, oldVal, scope) {
        // newVal is the current value of $scope.bar
        // oldVal is the previous value of $scope.bar
        // scope === $scope
        $log.log('bar watcher', newVal, oldVal, scope);
    });
    
    // invoked once every $digest cycle
    $scope.$watch(function(scope) {
        // scope === $scope
        $log.log('global watcher', scope);
    });
});