0

I am deep watching an object in Angular,

$scope.$watch('bigObject', function(newVal, oldVal, scope) { //Watch the whole object
    console.log("The key that changed was: " + key);
}, true); //Deep watch

How do I get the key that changed?

Example output: The key that changed was: bigObject.users.john.birthday

Machavity
  • 30,841
  • 27
  • 92
  • 100
adelriosantiago
  • 7,762
  • 7
  • 38
  • 71

1 Answers1

0

Try for this:

 $scope.$watch('bigObject', function (newValue, oldValue, scope) {
    //Do anything with $scope.letters
    if(oldValue.users.john.birthday == newValue.users.john.birthday){
      //nothing chages
    }
    else{
       // write your logic here after changinging value    
      }
            console.log(newValue.users.john.birthday);
  });
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21
  • Thanks but I am not trying to get the value itself. I'm trying to get the key that changed. – adelriosantiago Oct 09 '17 at 08:09
  • but it should be insure that your users, object must have john object and john object must have birthday property – Kunvar Singh Oct 09 '17 at 08:09
  • What do you mean? The key wouldn't change, the key (birthday in the example) would be the same. – adelriosantiago Oct 09 '17 at 08:11
  • Now i have ediited in my answer so plz try for that – Kunvar Singh Oct 09 '17 at 08:12
  • Thanks, but still not what I'm looking for. Imagine it like a logger, I want to log all keys that change. I can't know which key is going to change. In fact I have no information about the object itself. – adelriosantiago Oct 09 '17 at 08:14
  • No problem, $watch is always subscribing to that object, whenever you wiil change in bigObject, But i think we need to check, what parameter of the object is changing, thats why we wrote condition in our case. otherwise how we can detect, in case of chaging, it will automatically called. and implement your business logic. – Kunvar Singh Oct 09 '17 at 08:18