【问题标题】:Initialization order for ES6 imports and angular controllersES6 导入和角度控制器的初始化顺序
【发布时间】:2015-06-26 14:48:27
【问题描述】:

正在努力让 AngularJS 应用程序在 ES6 上运行。从历史上看,我一直使用允许控制器文件向应用程序注册自己的模式,因为这样我就不用担心文件定义了哪些控制器、服务等。使用 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>

【问题讨论】:

    标签: javascript angularjs ecmascript-6 es6-module-loader


    【解决方案1】:

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

    【讨论】:

    • JS文件比较多,是为了注意问题。
    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多