2

I'm using an initialization function init() within most of my controllers to setup controller specific variables. I'm finding I'm doing it in most controllers so I assuming this is common but I cannot find any documentation. As I see the options are as follows:

  1. leave as is
  2. use run or provider service

    (function () {
    
    'use strict';
    
    CompanyController.$inject = ['CompanyFactory','LocationService'];
    function CompanyController(CompanyFactory,LocationService) {
    
        let vm = this;
    
          // Initialize function  
        function init() {
            vm.company = {
                solutions: CompanyFactory.getSolutions(),
            };
            // set $location 
            LocationService.setLocation('company-page');
        }
    
        init();
    
    }
    
    angular.module('app.company', [])
        .controller('CompanyController', CompanyController)
    
    
    })();                          
    
2
  • What do you want?please explain more Commented Dec 22, 2017 at 6:25
  • There is no options. I believe.You have to make init() calls in each controller. Commented Dec 22, 2017 at 6:28

1 Answer 1

3

Controller lifecycle hooks were introduced in AngularJS 1.5. $onInit hook is supposed to play exactly this role:

this.$onInit = function () { ... }

$onInit hook is a replacement for pre-link function. It is executed by the compiler. It may not be executed if a controller doesn't belong to a directive (ng-controller is a directive, too) but is instantiated directly with $controller, like route controller. In this case this.$onInit() should be called explicitly in constructor.

It should be noticed that in original snippet function init() {...} doesn't play significant role. It isn't exposed as a method, so it cannot help a controller to be more testable or extensible.

Sign up to request clarification or add additional context in comments.

3 Comments

It is related to components not to controllers.
@SlavaUtesinov Lifecycle hooks were introduced as a step towards A2. It is specific to compiler, not components. Lifecycle hooks are documented in components section because components benefited most from them.
@estus thank you! btw, I only placed the function it in the controller for brevity sake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.