3

When you're using a $watch method (with equality by value). Is there a way to see which object property was changed?

e.g.

/** * Save state of button: Cancelled */ $scope.$watch('buttons.cancelled', function(newValue, oldValue) { if(newValue != oldValue && newValue !== undefined) { privates.viewState.buttons.cancelled = $scope.buttons.cancelled; } }); /** * Save state of button: Booked */ $scope.$watch('buttons.booked', function(newValue, oldValue) { if(newValue != oldValue && newValue !== undefined) { privates.viewState.buttons.booked = $scope.buttons.booked; } }); 

Turned into;

 $scope.$watch('buttons', function(newValue, oldValue) { if(newValue != oldValue && newValue !== undefined) { //Is there a way to know which button triggered this watch? } }, true); 
1
  • 1
    Well, you have the newValue and oldValue so you got to do the comparison yourself (if(newValue.booked !== oldValue.booked){'booked changed!'}). Commented Jan 14, 2014 at 15:19

1 Answer 1

1

Here is an example.

I would also like to see an angular built-in feature but as for now You need to do that manually

I put the buttons inside array of objects rather than in hash keys because:

$watch is invoked with new Value and old Value, just compare them :

$scope.buttons = [ { name: 'cancelled', checked: false}, { name: 'booked', checked: false}, { name: 'something', checked: false} ]; $scope.$watch('buttons',function(newVal,oldVal){ oldVal = oldVal.reduce(function(p,k){ p[k.name] = k.checked; return p;},{}); var changed = newVal.filter(function(k){ return oldVal[k.name] !== k.checked; }); changed = changed.reduce(function(p,k){ p[k.name] = k.checked; return p;},{}); $scope.changed = changed; },true); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.