Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $watch not working?

Tags:

angularjs

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>
like image 763
Sorin Comanescu Avatar asked Feb 08 '26 04:02

Sorin Comanescu


1 Answers

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)

like image 193
Florian F Avatar answered Feb 12 '26 16:02

Florian F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!