0

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 invoke init() (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 of init() 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?

Community
  • 1
  • 1
jwa
  • 3,239
  • 2
  • 23
  • 54

1 Answers1

1

If you keep thins simple: one state and one controller per view, than it may make sense to use the $stateChangeSuccess event for your init stuff.

$scope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ 
    // transition completed
    // let's init things
}) 
Andre Kreienbring
  • 2,457
  • 11
  • 16