简体   繁体   中英

Initialization order for ES6 imports and angular controllers

Was working on getting an AngularJS application running on ES6. Historically I've used the pattern of allowing the controller files to register themselves with the application, since that way I don't have worry about what controllers, services, etc a file defines. Using require() I've been able to order the dependancies and initialization such that this is easy and makes it possible to focus on the controller file.

Looking at migrating to ES6 and use import rather than require() and am finding that the order dependent code is no longer working. Attached is a rough approximation (never run) version of what I would like to do.

The only thing I've figured out is that it's possible to export a RegisterIndexController() function from index.js then have it called by app.js. Which works, but wondering if I could push the dependency the other way. Where a controller can be passed "app" from app.js

app.js

app = angular.module('app', ['ui.router'])

angular.element(document).ready(() => angular.bootstrap(document, ['app']))

import './controllers/index'

app.run(() => {
    })

index.js

app.controller('IndexController', IndexController)

class IndexController {
    /*@ngInject*/
    constructor() {
        this.count = 10
    }
}

index.html

<div ng-controller="IndexController as vm">
  {{ vm.count }}
</div>

ES6 imports are hoisted to the top of the file, so you cannot rely on ordering like this. The core of the issue for you is that you're relying on a implicit dependency ( app ) that isn't defined anywhere. Explicitly importing app would ensure that you actually get things in order.

Also note, class declarations are not hoisted, so your controller registration is in the wrong order.

app.js

export default angular.module('app', ['ui.router']);

index.js

import app from '../app';

app.controller('IndexController', class IndexController {
    /*@ngInject*/
    constructor() {
        this.count = 10
    }
});

entry.js

import app from './app';
import './controllers/index'

angular.element(document).ready(() => angular.bootstrap(document, ['app']))

app.run(() => {
})

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