Your controllers should be thin. This is a common refrain when discussing maintainable Angular code. It is true but it can be more difficult to implement in practice. My proposal is to use simple comments to separate the lines of code in your controller:
- Initialization values
- assigning your variables and items on
$scope
- assigning your variables and items on
- Private methods that are only used in the controller
- Methods that are used in the view
- CRUD
- $watches
- Getting data for the view
- call a
get
request to populate the view with data on initialization
- call a
- (hacks)
- hacks happen. Inspired by CSS Wizardy’s shame.css, labeling your hacks as such goes a long in maintainability.
Let’s imagine a photo editing application, and the route at /photo/123/edit
. This page would need to do the following:
- Fetch the photo from the API
- Allow posting to the API with updates to the photo
- Allow the user to reset the form.
- $watch something
The controller quickly becomes non-trivial. If we begin to need to add extra functionality (i.e. the ability to upload a watermark, the ability to offer extra editing features to premium users), then the controller could become even larger.
I would imagine the controller looking something like this: