hadi.mansouri
hadi.mansouri

Reputation: 828

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?

Upvotes: 2

Views: 1966

Answers (2)

Srinivas ML
Srinivas ML

Reputation: 730

We can use Equality $watch by passing third argument as true , as per API reference $watch accepts three arguments as below

$watch(watchExpression, listener, [objectEquality]);

if third argument is true , it will watch all properties inside a object

$scope.$watch("content",function(){},true);

for more info on $watch you can refer below video https://www.youtube.com/watch?v=IKPrhB8alV4

Upvotes: 0

Karl Reid
Karl Reid

Reputation: 2217

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.

Upvotes: 7

Related Questions