fahad tufail
fahad tufail

Reputation: 615

Is "$onInit", more efficient way than "activate" to activate "controller" in angularJS?

I'm new to angularJS and want to implement the efficient thing for my project but got stuck between $onInit (life cycle hook) and activate().

Upvotes: 0

Views: 1495

Answers (2)

georgeawg
georgeawg

Reputation: 48968

The use of activate() is a matter of opinion as it is a style recommended by some opinionated style guides.

On the other hand, the $onInit Life-Cycle Hook is invoked by the $compile service.

From the Docs:

Life-cycle hooks

Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the directive:

  • $onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

AngularJS $compile Service API Reference - Life-Cycle Hooks

Upvotes: 0

Michael Lynch
Michael Lynch

Reputation: 1743

Creating an activate() function inside of your controller and calling it directly is quite different than using the $onInit() lifecycle hook provided by AngularJS.

From https://docs.angularjs.org/guide/component#component-based-application-architecture:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

So basically the activate() function will be called as soon as your controller is constructed. Where as the $onInit() function will be called after all bindings have be successfully bound. Thus if you try to access your bound variables within your constructor, they will not be initialized yet.

Upvotes: 4

Related Questions