Technology, Continued...

Ramblings about business, technology, development and my life


Angular Gotcha – Watch out for Intra-Digest Changes!

The other day I had an issue with Angular that I hadn’t expected.  The deal was that I had the following scenario:

  • Changed the value of a scope variable.
  • Had a watch based on that scope variable changing.  The watch would trigger a DOM change.
  • Changed the value of the variable back to what it was.

Straightforward.  I expected the DOM to be changed.  But it didn’t.  What I forgot was that if the change from one value back again happened during the same digest cycle, it could be like it never happened as far as any watch expressions were concerned.

The idea of the digest cycle is something you have to understand deeply to really be good at Angular.  However, a scenario like this doesn’t happen enough for it to be something you watch for proactively, as opposed to reacting when the bug pops up.  But now, when writing Angular controllers and directives, I’m seeing places more and more in which I need to be aware of the implications. 

What I’d like to see in Angular is a way to force evaluation of watches from within a controller method.  As it stands now, you can’t force the apply/digest, because when in a controller method, you’re in the middle of one.  Having a method like $forceWatchEval() would be wonderful.  Easy for me to say… I’m sure there are complications in the Angular lifecycle that would probably make that harder than it seems.  And while I’ve explored some of the Angular source already, I don’t have time to dig this deeply, and even if I did, Angular v2 is going to change things drastically anyway.