【问题标题】:Hybrid Angular 1.x + Angular 6 App with both vanilla JS and TS files in Angular 1.x混合 Angular 1.x + Angular 6 应用程序,在 Angular 1.x 中包含 vanilla JS 和 TS 文件
【发布时间】:2019-02-01 06:47:28
【问题描述】:

当 AngularJS 文件同时是 JS 和 TS 时,我正在尝试构建一个混合应用程序。 我似乎无法向 JS 控制器添加路由。

我依赖以下example 并执行以下操作:

const statesConfigBlock = ['$stateProvider', $stateProvider => {
  $stateProvider.state('main', {
    url: '/main',
    templateUrl: 'app/components/layout/mainView.html',
    controller: 'mainController as main'
  })
}];
appModuleAngularJS.config(statesConfigBlock);

虽然我有一个定义为 mainCtrl.js 的文件:

var app = angular.module('myApp', []);

(function(app) {
  'use strict';

  app.controller('mainController', [
      function () {
        console.log("blah");

      }]);
})(app);

当我运行应用程序时,我得到:

名为“mainController”的控制器未注册

但我在控制台中运行时确实看到了它:

angular.module('myApp')._invokeQueue.filter(function(el){
  return el[0] === "$controllerProvider";
}).map(function(el){
  return el[2]["0"];
});

【问题讨论】:

  • 您能说明appModuleAngularJS 的定义位置吗?
  • @yadejo 与 sampleAppModuleAngularJS here 相同

标签: angularjs angular angular-ui-router angular-hybrid


【解决方案1】:

好的,我想我成功了。这可能不是最好的解决方案,但可以。

首先,我创建了一个包含模块声明的 js 文件:

appDependencies = [];
app = angular.module('myApp', appDependencies);

所有 Angular 1.x 控制器和服务都使用全局变量 app,如下所示:

(function(app) {
  'use strict';

  app.controller('mainController', [
      function () {
        console.log("blah");

      }]);
})(app);

最后,Angular 1.x 模块 ts 文件使用全局 app 并为其添加依赖项:

...

declare const app: any;
declare var appDependencies: any;

export const appModuleAngularJS = app;

angular.forEach([
  uiRouter, upgradeModule.name
], module => {
  appDependencies.push(module);
});

...

const statesConfigBlock = ['$stateProvider', $stateProvider => {
  $stateProvider.state('main', {
    url: '/main',
    templateUrl: 'app/components/layout/mainView.html',
    controller: 'mainController as main'
  })
}];
appModuleAngularJS.config(statesConfigBlock);

...

现在,index.html 文件中 js 导入的顺序非常重要。 app 减速文件应该首先出现,然后是所有 Angular 1.x 控制器和服务,然后是被转译为 js 文件的 *.ts 文件。

这个解决方案对我有用,但我很高兴看到一个更好的解决方案。

干杯!

【讨论】:

  • 感谢回复,我看看
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
  • 2018-09-20
  • 2016-05-23
  • 2016-03-29
相关资源
最近更新 更多