Search code examples
javascriptangularjsangularjs-watch

Watch on all attributes of an object in AngularJS


I have an object in my $scope which contains some attributes such as following:

$scope.content = {
     name : 'myname',
     description : 'mydescription',
     keyword : 'some keyword'
}

Now I want to listen on every change in each attribute. I set watch on its own object but I could not get changes on its attributes (its attributes are changed from UI by binding to some input fields).

$scope.$watch('content', function(){
     // do some work
}

When I set watch on some attribute as follow, I can get changes in that attribute.

$scope.$watch('content.name', function(){
     // do some work
}

Is there any way to listen to change of attributes of object without set watch on all attributes?


Solution

  • Use the third argument of $watch, like this :

    $scope.$watch('content', function(){
         // do some work
    }, true);
    

    If this is true, the expression is evaluated for object equality, which means properties are included. Otherwise it's just evaluated for reference.