AngularJS error: [ng:areq] Argument 'TestController' is not a function, got undefined

AngularJS error: [ng:areq] Argument 'TestController' is not a function, got undefined

我正在尝试制作我的第一个控制器并收到此错误:

错误:[ng:areq] 参数 'TestController' 不是函数,未定义

我已经简化了我的代码以找到错误,但没有成功。在我看来,我正在脚本中创建控制器和书籍数组,并在 div 中逐个字母地引用控制器。我错过了什么?

<!doctype html>
<html data-ng-app>
<head>
    <meta charset="utf-8"/>
</head>
<body>

    <div data-ng-controller="TestController">
        <ul>
            <li data-ng-repeat="b in books">{{ b.title + ' by ' + b.author }}</li>
        </ul>
    </div>

    <script src="angular.js"></script>
    <script>
        function TestController() {
            this.books = [{title: 'Angela', author: 'Donald Duck'}, {title: 'Angles', author: 'Dirty Harry'}];
        }
    </script>
</body>
</html>

自从全局函数在 angular.js 中不再是控制器以来已经有很长一段时间了。您需要在您的模块中将该函数注册为控制器:

<html ng-app="myApp">

在JS代码中:

angular.module("myApp", []).controller('TestController', function($scope) {
    $scope.books = ...;
});

您的 angular 知识已经过时了。重新阅读文档。

或更简单的方法

angular.module("myApp", []).controller('TestController', TestController);

function TestController($scope) {
$scope.books= [{title: 'Angela', author: 'Donald Duck'}, {title: 'Angles', author: 'Dirty Harry'}];

}