8

In AngularJS, what is the purpose of the $onInit function if I can do the same initialization without that function?

For example this:

module.component("myComponent", {
        ...
        controller: function() {
            const $ctrl = this;

            $ctrl.$onInit = () => {
                $ctrl.var1 = "hello";
                $ctrl.var2 = { test: 3 };
            }
        }
    });

Can also be done like this:

module.component("myComponent", {
        ...
        controller: function() {
            const $ctrl = this;

            $ctrl.var1 = "hello";
            $ctrl.var2 = { test: 3 };
        }
    });

Is there some case where $onInit is necessary?

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • 1
    With the release of AngularJS V1.7, the option to pre-assign bindings to has deprecated and removed. Initialization logic that relies on bindings being present should be put in the controller's `$onInit()` method, which is guaranteed to *always* be called after the bindings have been assigned. – georgeawg Nov 25 '19 at 20:12

1 Answers1

12

Per the AngularJS docs

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 gives you two guarantees:

  1. All controllers on this element have been constructed
  2. The pre & post linking functions for this element have not been executed

In contrast to your first method, where neither of these facts are guaranteed (though the second one is highly probable).

In addition, as a matter of style and readability, it makes it very clear to a potential reader/reviewer that this is code that you as the developer intended to run upon initialization of this controller.

rmlan
  • 4,387
  • 2
  • 21
  • 28