vinesh
vinesh

Reputation: 4913

AngularFire: How to $watch on child of an object?

I want to listen changes done to a particular child of an object. For ex. I have data stored in firebase as

users: {
  user1:{
    info:{ name: 'Jon', age:'21'},
    otherThings:{}
  },
  user2:{
    info:{ name: 'Mark', age:'20'},
    otherThings:{}
  }
}

Now, I can listen to changes in user1 by

$scope.userObj = $firebase(userRef).$asObject();
$scope.userObj.$watch(function() {
   console.log("data changed!");
});

But is there any way to listen to changes only when its child i.e. $scope.userObj.name changes?
It should be with userObj only, userObj.child('name') or something like that.

Upvotes: 1

Views: 1952

Answers (1)

Kato
Kato

Reputation: 40582

Angular's $watch command accepts dot notation. Just watch the appropriate field demo:

$scope.$watch('userObj.info.name', callback);

Read more in the $scope docs. This is pretty much Angular 101.

But most likely, this is the wrong approach. Any time you start trying to $watch and manipulate data in the controller, you've probably went down the wrong route. Let the view handle watching, and do data transformations either in a service or (in AngularFire's case) using data transformations like $extendFactory.

Upvotes: 1

Related Questions