angularjsangularjs-controllerangularjs-compileangularjs-lifecycle

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


Solution

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