Pages

February 10, 2015

Stop and Resume Binding in AngularJS

Hi,

There comes a time when you need to tweak the native behavior of a framework.
For me it was pretty straight forward desire to stop and resume binding for DOM elements.

The reason behind it was that sometimes I have several elements on the DOM which listen to the same data, but not all of them are viewable. Only one of them is viewable and this is the one I would like the binding to keep updating, while the rest shut the hell up and do nothing over the data changes.

AngularJs is not too kind when it comes to tempering with it's biding mechanism and I guess they have they reasons. The binding mechanism is something that can dramatically affect the performance of an application.

If you go little bit deeper (really, no too deep) you find that binding is all about the digest cycle which in turn invoke watchers, which are functions set to watch for changes and invoke callback accordingly. It is these $$watchers which you would like to remove and retrieve in order to connect and disconnect to the digest cycle.

I've made a simple POC where I created DOM with 2 identical directive bound to the same data on their parent scope. I also added buttons to toggle their binding - pressing it once cuts off the binding for a specific directive while the other keeps on updating. Another click resumes the binding.

Simple - you can find the code here on Plunker

Take care.