0

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
fahad tufail
  • 555
  • 4
  • 10
  • The question would be clearer if you cite the style guide that recommends using an `activate()` method. The use of `activate()` is a matter of opinion as it is a style recommended by some *opinionated* style guides. The AngularJS $compile service invokes the `$onInit` [Life-Cycle Hook](https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks) after it binds attributes to the controller. – georgeawg Aug 17 '18 at 17:19

2 Answers2

4

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Michael Lynch
  • 1,743
  • 15
  • 27
0

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

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95