Sorin Comanescu
Sorin Comanescu

Reputation: 4867

Angular $watch not working?

The code below only logs when the page is initially loaded. What's wrong?

<!DOCTYPE html>
<html ng-app>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
    </head>
    <body>
        <div ng-controller="PageController">
            <p ng-bind="model.header"></p>
            <p>Value: <input ng-model="model.header" /></p>
        </div>
        <script>
            function PageController($scope) {
                $scope.model = {};
                $scope.model.header = 'Header';

                $scope.onModelChange = function (newValue, oldValue, scope) {
                    console.log('model changed > newValue: ' + newValue + ' > oldValue: ' + oldValue);
                };

                $scope.$watch($scope.model, $scope.onModelChange, true);
            }
        </script>
    </body>
</html>

Upvotes: 2

Views: 13346

Answers (2)

Craig Squire
Craig Squire

Reputation: 2141

As Florian F mentioned, the first argument is a string of the scope property you want to watch.

$scope.$watch("model", $scope.onModelChange, true);

But, as you are watching for changes to model.header, the 'deep' parameter does need to be set. If not true, the watch will only be triggered if the model object reference itself is updated.

Here's a plunkr showing both a shallow and deep watch where the shallow watch will not work because it's only watching the model object reference. http://plnkr.co/edit/ejMc2pBjIFD9aX6PBsY1

Upvotes: 5

Florian F
Florian F

Reputation: 8875

The first argument of $watch should be the scope property itself

$scope.$watch("model", $scope.onModelChange);

And you don't need to enable a deep watch on this property (third argument)

Upvotes: 14

Related Questions