2

I have a watch set up to track when a property in my service changes. When the property changes, i need to make an AJAX call to a webservice, however, when the property DOES change, the watch is firing twice. I have tried checking newValue !== oldValue but when I log their respective values to the console, the first time the watch fires it look like this:

newValue: MyObject, oldValue: undefined

and then when it fires immediately after, they are identical to the first time:

newValue: MyObject, oldValue: undefined

The problem this causes is that 2 AJAX calls get made instead of 1. How do I get the watch to fire the function once?

Jonathan Smith
  • 2,390
  • 1
  • 34
  • 60
  • 5
    Could you provide some more information, e.g. the code of the $watcher as well as the ajax-call? – David Losert Jul 24 '14 at 11:50
  • 1
    Please provide your code, maybe it has his own watcher and you adding another watcher on that – Milad Jul 24 '14 at 12:49
  • 1
    Just wanted to add a comment that the $watch listeners will fire upon initialization if it is tied to a $scope variable. You would need to add a conditional within your $watch listener to look for 'oldValue === newValue' to know if it was caused by initialization or not. (http://stackoverflow.com/questions/20942930/angular-expressions-in-watch-trigger-twice/20942931#20942931) Based on your question this doesnt seem to be your problem, but just wanted to point that out. – glandrum101 Jul 24 '14 at 14:16

0 Answers0