Targaryen Targaryen - 2 months ago 13
Node.js Question

Argument 'MainController' is not a function, got undefined

I tried re-writing my Angular app using TypeScript, but it is not working. MainController is not a function?

I am using Visual Studio's TypeScript UMD Compiler and I am trying to run this app in a Nodejs/Expressjs server I setup on my local machine.

Here is how I define my app in myApp.js:

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


Here is the controller in MainController.ts:

export class MainController {
public USER_DATA: any;

constructor(private $scope: ng.IScope) {
//constructor
}
}

angular.module('myApp')
.controller('MainController', ['$scope', MainController]);


This is a small piece of what the compiled JavaScript in MainController.js looks like:

(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "MyAppExports"], factory);
}
})(function (require, exports) {
"use strict";
var MainController = (function () {
function MainController($scope) {
var _this = this;
}
return MainController;
}());
exports.MainController = MainController;
angular.module('myApp')
.controller('MainController', ['$scope', MainController]);
});


And here is index.html...

<html>
<body ng-app="myApp">
...
<div class="container" ng-controller="MainController">
<a href="#">Notifications <span class="badge">{{USER_DATA.notifications.length}}</span></a>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<script src="myApp.js"></script>
<script src="MainController.js"></script>

</body>
</html>


Why am I getting an error that MainController is not a function?

Answer

Why am I getting an error that MainController is not a function?

Because your file is JavaScript module because of the export in export class MainController {.

More on modules : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

You need a module bundler. There are a few options but I (and the angular 2 team) recommend webpack. Quickstart : https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html

Comments