Whisher
Whisher

Reputation: 32716

Angularjs watch a object in a form doesn't work

Can you explain me why this simple code doesn't work I want see the change of user object in the controller.

<!doctype html>
 <html ng-app="myApp">
    <head>
        <meta charset="utf-8">

    </head>
    <body>
        <div data-ng-controller="MainCtrl">
            <h1>User Info</h1>
                <form novalidate id="my-frm" name="myFrm">
                    <label>Last name</label>
                    <input type="text" ng-model="user.lastName">
                    <label>First name</label>
                    <input type="text" ng-model="user.firstName">
                    <p ng-click="add()">add</p>
                </form>
        </div>
        <script src="http://code.angularjs.org/1.0.8/angular.min.js"></script>
        <script>
            var app = angular.module('myApp', []);

            app.controller('MainCtrl',function($scope,$log){
                $scope.user = {};
                $scope.add = function(){
                    $log.info($scope.user);
                };
                $scope.$watch(
                    function(){
                        return $scope.user;
                    },
                    function(n,o){
                       $log.info(n);
                       $log.info(o); 
                    }
                );

            });
        </script>
    </body>
</html>

Upvotes: 1

Views: 2318

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

Try this:

$scope.$watch("user", function(n, o) {
    ...
}, true);

Hopefully it is usable in Angular 1.0.8.

What this does is to instruct Angular to do a "deep watch" to your object. Also, since the user is in the $scope, you can specify the dependency using just a string. This is optional, you can still use the function instead of "user" as the first argument to $watch.

Upvotes: 4

Related Questions