Angular JS Controller On Init

Examples that show the universality of the $onInit lifecycle callback in AngularJS. View the source of this page and the script for more details.

Scoped Angular JS controller

This is a traditional Angular controller that uses $scope. In this case, this is how you write the controller function:

    function ScopedControllerFunc($scope) { 
        this.$onInit = function() {
            $scope.did_on_init = true;
        };
    }
            

Was on init called? Yes! No!


CtrlAs Angular JS Controller

This is an Angular Ctrl that uses CtrlAs. In this case, this is how you write the controller function:

    function CtrlAsControllerFunc() { 
        var $ctrl = this;
        $ctrl.$onInit = function() {
            $ctrl.did_on_init = true;
        };
    }
            

Was on init called? Yes! No!


Controllers Within Directives

This is an Angular Ctrl within a Directive. In this case, this is how you write the controller function:

    function CtrlAsControllerFunc() { 
        var $drctv = this;
        $drctv.$onInit = function() {
            $drctv.did_on_init = true;
        };
    }
            

Controllers Within Components

This is an Angular Ctrl within an Component. In this case, this is how you write the controller function:

    function CtrlAsControllerFunc() { 
        var $ctrl = this;
        $ctrl.$onInit = function() {
            $ctrl.did_on_init = true;
        };
    }
            

Controllers Initialized by ngRoute

This is an Angular Controller that's initialized by the ngRoute module. This is the one major area I could find where $onInit is not called.