Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use $onInit in AngularJS? [duplicate]

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?

like image 225
Daniel Avatar asked Feb 01 '18 22:02

Daniel


People also ask

What is $OnInit in AngularJS?

A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

What does ng init do in AngularJS?

The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.

What is $Ctrl in AngularJS?

$ctrl is the view model object in your controller. This $ctrl is a name you choose (vm is another most common name), if you check your code you can see the definition as $ctrl = this; , so basically its the this keyword of the controller function.

Which one is called first ngOnInit or constructor?

OnInit : ngOnInit is component's life cycle hook which runs first after constructor(default method) when the component is being initialized. So, Your constructor will be called first and Oninit will be called later after constructor method.


1 Answers

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.

like image 171
rmlan Avatar answered Oct 16 '22 22:10

rmlan