首页 > 解决方案 > 找不到 AngularJS + Typescript 控制器

问题描述

我正在尝试将打字稿添加到 AngularJS,但出现以下错误

Error: [$controller:ctrlreg] The controller with the name 'MyController' is not` registered

有没有人知道我做错了什么?

我创建了以下类

/// <reference path='references/_all.ts' />
var app = angular.module('shop', []);

class MyController {
    constructor($scope: any) {
        $scope.message = { title: "Hello World!!" };
    };
}

app.controller('MyController', MyController);

和html:

<html>
<head>
...
</head>
<body ng-app="shop">
    <div ng-controller="MyController">
            {{message.title}}
    </div>
</body>
</html>

我正在使用 grunt 来编译它:

/// <reference path='references/_all.ts' />
var app = angular.module('shop', []);
var MyController = (function () {
    function MyController($scope) {
        $scope.message = { title: "Hello World!!" };
    };

    return MyController;
})();
app.controller('MyController', MyController);

标签: javascriptangularjstypescript

解决方案


你有应用程序的链接文件吗?

<script src="./app.js"></script>

这是我的解决方案:

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

var MyController = (function () {
    function MyController($scope) {
        $scope.message = { title: "Hello World!!" };
    }

    return MyController;
})();

app.controller('MyController', MyController);
<head>
  <meta charset="utf-8" />
  <title>AngularJS + Typescript controller cant be found</title>
  <script src="https://code.angularjs.org/1.5.4/angular.js"></script>
  <script src="./app.js"></script>
</head>

<body ng-app="shop">
  <div ng-controller="MyController">
      {{message.title}}
  </div>
</body>
</html>


推荐阅读