Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the lifecycle of an AngularJS Controller?

People also ask

What is life cycle of AngularJS?

Now that you understand the components involved in an AngularJS application, you need to understand what happens during the life cycle, which has three phases: bootstrap, compilation, and runtime.

What are the controllers in AngularJS?

In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.

Which of the following is AngularJS module life cycle phase?

Life cycle, which has three phases: bootstrap, compilation, and runtime. Understanding the life cycle of an AngularJS application makes it easier to understand how to design and implement your code. The three phases of the life cycle of an AngularJS application happen each time a web page is loaded in the browser.

Does AngularJS have lifecycle hooks?

Lifecycle hooks are simply functions that get called at specific points of a component's life in our Angular apps. They landed in AngularJS 1.5 and are to be used alongside the . component() method, and have slowly evolved over the last few versions to include some more powerful (and Angular v2+ inspired) hooks.


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).