ES6 导入和 angular 控制器的初始化顺序

Initialization order for ES6 imports and angular controllers

正在努力在 ES6 上获得 AngularJS 应用程序 运行ning。过去,我使用过允许控制器文件在应用程序中自行注册的模式,因为这样我就不必担心文件定义了什么控制器、服务等。使用 require() 我已经能够对依赖项和初始化进行排序,这样就很容易,并且可以专注于控制器文件。

考虑迁移到 ES6 并使用 import 而不是 require(),我发现依赖于顺序的代码不再有效。附件是我想做的粗略近似(从来没有 运行)版本。

我唯一想到的是可以从 index.js 导出 RegisterIndexController() 函数,然后让 app.js 调用它。哪个有效,但想知道我是否可以以另一种方式推动依赖性。可以从 app.js

传递控制器的地方 "app"

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 导入被提升到文件的顶部,所以你不能依赖这样的排序。对您而言,问题的核心是您依赖于未在任何地方定义的隐式依赖项 (app)。显式导入 app 将确保您真正按顺序进行操作。

另请注意,class 声明未提升,因此您的控制器注册顺序错误。

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(() => {
})