The (Almost) Universality of the $onInit Lifecycle Callback in AngularJS

AngularJS 1.x's Component functionality brought with it new lifecycle callbacks that are not restricted to controllers within Components.

Posted by Tejus Parikh on February 4, 2017

Far from being dead, AngularJS is incorporating new functionality that keeps it a solid alternative to the newer frameworks that have appeared. This is great news for those developers (like me!) that started using Angular in their current projects from before the 1.0 days.

With that great news comes a few caveats. Consistency has never been a strong suite of Angular 1.x and often it can be unclear if the new features will work correctly within code that follows the older recommended way of doing things. I recently had just that question about the $onInit callback introduced in Angular 1.5 that is a requirement in Angular 1.6.

I created an example project to test different situations (direct link to github).

The sample code shows that in almost every case where you use a Controller, you can use the $onInit callback. This includes using $onInit in Directives, Controllers on elements, Controllers defined with ControllerAs, and of course Components. The one case it does not work is Controllers defined in routes used by ngRoute. No surprise that the Angular router is the odd ball out. Unfortunately this is not something the ngRoute team appears to want to remedy.

This means that if you have pre Angular 1.5 code and want to upgrade to Angular 1.6, you can and should use $onInit everywhere except for Controllers that are used for routes, which you will have to keep using the previous way. AngularJS always has a way of keeping developers on their toes.

Original image is CC-licensed [original source]

Tejus Parikh

I'm a software engineer that writes occasionally about building software, software culture, and tech adjacent hobbies. If you want to get in touch, send me an email at [my_first_name]@tejusparikh.com.