Chapter 8. Refactoring Controllers

In my experience over multiple enterprise Angular applications, controllers are constantly the biggest source of trouble in Angular applications. Controllers tend to be given far too many responsibilities while simultaneously resisting reuse. The use of inherited scope makes it difficult to trace the origin of methods and properties accessed from a child scope. Most of the work in refactoring Angular applications comes from moving code out of controllers and into pieces that are easier to work with.

The refactorings in this section are variations on relocating application features from controllers into components better suited for maintenance and reuse. Moving features out of controllers is higher-risk refactoring because controllers by their nature resist reusability and foster code that is difficult to reach through testing.

How can we refactor these complicated components? The answer lies in the techniques we’ve already discussed: unit testing, style guide usage, separating concerns into their own modules and files, and moving logic out of view templates and into JavaScript. Moving code out of controllers is a demanding task that requires a developer’s full attention. It’s work that needs to be done slowly and deliberately.

Controllers Contain the Highest-Risk Code

Controllers in Angular have limited means of sharing functionality, lack a useful set of lifecycle hooks, and and are not singletons. Despite these weaknesses it’s typical to find ...

Get Refactoring Angular Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.