Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Last active May 23, 2016 15:01
Show Gist options
  • Save bvaughn/012fb525e6c819fdc9bf to your computer and use it in GitHub Desktop.
Save bvaughn/012fb525e6c819fdc9bf to your computer and use it in GitHub Desktop.
Debugging Angular bindings

This afternoon I encountered a race condition in an Angular app I'm working on. Essentially my controller was pushing some values to an Array on its scope and something (I wasn't sure what) was asynchronously overriding the Array's contents. The Array was being used by a custom directive- written by someone else- as well as an ngModel and it wasn't clear who was making the change.

I ended up trying something I had not done before and it worked well enough that I thought I'd post it here in case it helped anyone else.

First I enabled The "Async" option in Chrome's "Sources > Call Stack" panel.

Next I set a breakpoint in my controller where I was modifying the Array. When I hit that breakpoint, I ran the following code in my console:

Object.observe(this.theArray, function(changes) {
  debugger;
});

Then I resumed script execution. A second later, my debugger statement hit and the async stack trace showed that ngModel was updating my Array.

Pretty simple approach but really useful when you don't know what is triggering a change to one of your scope objects.

@bvaughn
Copy link
Author

bvaughn commented Apr 17, 2015

Good call. If I had been debugging a property of an object I probably would have done the same- but since I wasn't sure what was being changed (was the array being spliced? Was it a different array entirely?) I decided to go with a couple of Object.observes. Both are powerful debugging tools!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment