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().
Is "$onInit", more efficient way than "activate" to activate "controller" in angularJS?
1.4k views Asked by fahad tufail At
2
There are 2 answers
0
On
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
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:
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.