How $watch works

by Ahmad Baktash Hayeri

HTML

<div ng-controller="theCtrl">
    <some-dir my-var="myVar"></some-dir>
    <other-dir my-var="myVar"></other-dir>
    <h3>
  Check your console
  </h3>
    <button ng-click="buttonClicked()">
        click me
    </button>
</div>

JavaScript

angular.module('theapp', [])
    .controller('theCtrl', ['$scope', function($scope) {
        $scope.myVar = {};
        $scope.myVar.subVar = 1;



        $scope.buttonClicked = function() {
            $scope.myVar.subVar++; // This will trigger $watch expression to kick in
            //console.log($scope.myVar);
        };
    }])
    .directive('someDir', function() {
        return {
            restrict: "E",
            scope: {
                myVar: '='
            },
            link: function(scope, iElement) {
                scope.$watch('myVar.subVar', function() {
                    console.log('watching in some directive ... myVar.subVar was changed');
                    console.log(scope.myVar);
                });
            }
        };
    })
    .directive('otherDir', function() {
        return {
            restrict: 'E',
            scope: {
                myVar: '='
            },
            link: function(scope, iElement) {
                scope.$watch('myVar.subVar', function() {
                    console.log('watching in other directive...');
                })
            }
        }
    })