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

Issue

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"];
});

Solution

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!

Answered By – Rony Fragin

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.