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:
- leave as is
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) })();
-
What do you want?please explain morebipin patel– bipin patel2017年12月22日 06:25:00 +00:00Commented Dec 22, 2017 at 6:25
-
There is no options. I believe.You have to make init() calls in each controller.Nikhil Mohanan– Nikhil Mohanan2017年12月22日 06:28:15 +00:00Commented Dec 22, 2017 at 6:28
1 Answer 1
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.