【问题标题】:AngularJS error: [ng:areq] Argument 'TestController' is not a function, got undefinedAngularJS 错误:[ng:areq] 参数“TestController”不是函数,未定义
【发布时间】:2016-03-24 17:00:32
【问题描述】:

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

错误:[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>

【问题讨论】:

  • 我正在学习教程,正如 JB Nizet 指出的那样,我的知识“过时”了。我发现它在 1.3.0-beta 的前半部分之后停止工作。

标签: angularjs angular-controller


【解决方案1】:

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

<html ng-app="myApp">

在JS代码中:

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

你的角度知识已经过时了。重新阅读文档。

【讨论】:

    【解决方案2】:

    或更简单的方式

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

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 2015-09-02
      • 2015-10-20
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 2015-11-03
      • 2016-10-23
      相关资源
      最近更新 更多