Javascript – How many Angular Controllers and/or Directives is too many

angularjsjavascriptperformance

I'm building a large, editable data table with angular, and I'm trying to figure out what the best practice is.

The table will be a couple of hundred rows, with a couple of dozen columns, so upwards of 2000 cells. Each cell needs to be editable inline.

My first thought was to have directives at the cell level, so it would look something like:

<editablecell model="some model expression"></editablecell>

But I'm concerned about the performance of creating thousands of directives instances, each with its own scope, controller, and event listeners. I'm worried that if the table needs to be redrawn (you change the sorting, for instance) the performance will suffer.

Is it a better idea to maybe have a per-row directive that has a meatier controller and template to handle all the data binding and event handling at a higher level, and thus create fewer child scopes and event listeners?

Best Answer

I wouldn't worry too much about the number of directives and controllers, at least not without performance data. Proper use of directives and controllers is what makes your page maintainable. It's about coming up with a re-usable set of components that you can mix and match.

The number of watchers can be problematic as it means that every digest cycle all those watchers will fire off. How much of the data is dynamic and how much is static?

For static data, Angular 1.3 added one-time bindings which can help you reduce the number of watchers. You can read about those here. If you're dealing with thousands of rows of dynamic data, I'm not sure there's really much you can do to optimize that. It simply takes a lot of time to update thousands of pieces of information. There may be some optimizations you can make with more information about the subjective case you're working on.

Related Topic