When writing AngularJS controllers, I often wonder where it would be best-placed to write initialization logic.
For the sake of this illustration, let's assume that I've separated-out my initialization logic into a separate init()
method.
As far as I can tell, I have three possible ways to invoke this as part of the controller start-up:
init in constructor - As per proposed solutions to other questions, you could invoke
init()
from the constructor. Initialization-in-constructor is widely accepted as an anti-pattern in most languages. I'm particularly against this because I have use-cases where I have class inheritance, and wouldn't want the parent constructor to invokeinit()
(which may have been overridden in the child class) before the child constructor has finished executing.ng-init - Invoke
init()
by using a ng-init` directive in the view. This isn't great, as it's coupling my view to the internal workings of my controller.delayed init from constructor - Use the
$timeout
service to schedule the invocation ofinit()
after a delay of 0 milliseconds. This will allow the child constructor to be fully executed before invoking the initialization logic.
None of these solutions seems like an overly clean way of solving such a basic problem. Are there alternatives that I have overlooked?