Hybrid Angular 1.x + Angular 6 App with both vanilla JS and TS files in Angular 1.x
Asked Answered
M

1

6

I'm trying to build a hybrid app when the AngularJS files are both JS and TS. I can't seem to add a route to a JS controller.

I'm relying on the following example and doing the following:

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

while I have a mainCtrl.js file that's defined as:

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

(function(app) {
  'use strict';

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

      }]);
})(app);

when I run the app I get:

The controller with the name 'mainController' is not registered

but I do see it when I run in console:

angular.module('myApp')._invokeQueue.filter(function(el){
  return el[0] === "$controllerProvider";
}).map(function(el){
  return el[2]["0"];
});
Marivaux answered 26/8, 2018 at 14:39 Comment(2)
Can you show where appModuleAngularJS is defined?Eliott
@Eliott same as sampleAppModuleAngularJS hereMarivaux
M
2

Okay, I think I managed to make it work. It might not be the best solution but here goes.

First, I created a js file that holds the declaration of the module:

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

All the Angular 1.x controllers and services use the global variable app like so:

(function(app) {
  'use strict';

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

      }]);
})(app);

Finally, the Angular 1.x module ts file uses the global app and adds dependencies to it:

...

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

...

Now, the order of the js imports in the index.html file is really important. The app deceleration file should come first, then all the Angular 1.x controllers and services and then the *.ts files that were transpiled to a js file.

This solution worked for me, but I'm more than happy to read a better one.

Cheers!

Marivaux answered 28/8, 2018 at 7:24 Comment(1)
Thanks for the response, ill take a lookPacifism

© 2022 - 2024 — McMap. All rights reserved.