What is the lifecycle of an AngularJS Controller?

Well, actually the question is what is the life cycle for a ngView controller.

Controllers are not singletons. Anyone can create a new controller and they are never auto-destroyed. The fact is that it’s generally bound to the life cycle of its underlying scope. The controller is not automatically destroyed whenever its scope is destroyed. However, after destroying an underlying scope, its controller is useless (at least, by design, it should be).

Answering your specific question, a ngView directive (as well for ngController directive) will always create a new controller and a new scope every time a navigation happens. And the last scope is going to be destroyed as well.

The life cycle “events” are quite simple. Your “creation event” is the construction of your controller itself. Just run your code. To know when it gets useless (“destruction event”), listen to scope $destroy event:

$scope.$on('$destroy', function iVeBeenDismissed() {
  // say goodbye to your controller here
  // release resources, cancel request...
})

For ngView specifically, you are able to know when the content gets loaded through the scope event $viewContentLoaded:

$scope.$on('$viewContentLoaded', function readyToTrick() {
  // say hello to your new content here
  // BUT NEVER TOUCHES THE DOM FROM A CONTROLLER
});

Here is a Plunker with a concept proof (open your console window).

Leave a Comment