简体   繁体   中英

AngularJS initialize controller variables

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) })(); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM