Sitemap

AngularJS One-time bindings and Recompiling Templates

For the non-trivial Angular Application

--

If you’ve worked on a sizeable AngularJS application, you’ll discover that while Angular’s digest cycle is awesome, it can also make your app seem sluggish as it grows and that digest cycle takes longer. So it becomes important to watch your watchers because even though one wont really cause an issue, the more you have, the worse it gets.

In an app I’m working on at work, we have areas of the app that can get a rather large watch count fast. Most pages sit at around 2,000, but some grow up to over 20,000 or 30,000! This can make the digest cycle take hundreds of milliseconds to complete resulting in a pretty janky experience for the users.

There’s Hope!

AngularJS version 1.3 will bring our expressions something called “One-time binding.” Basically, by adding two colons “::” to your expression, you tell Angular “hey, once this expression returns a value, stop watching it.” This can drastically reduce your watch count, particularly in an ng-repeat. And for those of you who can’t update just yet (1.3 is still in beta) you can take advantage of the bindonce module which attempts to do the same thing and does so decently well.

The Problem

So, let’s say you have something that does update, but does so infrequently and you know when it does (like a promise resolution or browser event). Well, you’re stuck watching anyway because Angular’s one-time binding wont listen for changes anymore. What you really need is a way to tell Angular to recompile the template…

A Solution! kcd-recompile

A directive that stores the template of its children and will recompile its children on demand. I’ve written just such a directive. It’s easy to use and it was a relatively small implementation

Get Kent C. Dodds’s stories in your inbox

Join Medium for free to get updates from this writer.

Usage:

https://gist.github.com/kentcdodds/a5b8e8dc4569c80e9a20

Implementation:

https://gist.github.com/kentcdodds/739566ebd3609ac95e61

This directive is one of several (and more to come) “Angular Things” that I’ve made (or found/modified) in my “kcd” module. Feel free to see the interactive demo site where you can play around with the demo and figure out how to use this directive: http://kentcdodds.com/kcd-angular/#/kcd-recompile

Press enter or click to view image in full size
Screenshot of the demo for kcd-recompile

I’m really looking forward to when Angular 1.3 is officially released and we can update where I work. For now, I’m using the kcd-recompile directive with bindonce and it is working splendidly. Good luck! And may your digest cycles always be short :-)

--

--