错误:Error:areq定义控制器时参数错误

Error: error:areq Bad Argument while defining a controller

本文关键字:错误 参数 控制器 areq Error 定义      更新时间:2023-09-26

这是我第一次尝试使用Angular。我正在尝试从互联网上运行现有的代码,它给出了错误:

Error: error:areq Bad Argument
Argument 'ngAddressListController' is not a function, got undefined

此代码与AngularJS<1.3,但在1.3+中出现问题

代码如下:

HTML

<!doctype html>
<html ng-app="">
<head>
    <title>Ng Addressbook</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
    <script src="main.js"> </script>
</head>
<body>
<div ng-controller="ngAddressListController">
    <h3>Ng Address Book</h3>
    <div id="container">
        <h3>There are 4{{contacts}} Contacts So far</h3>
        <ul>
            <li>
                <span>First Name</span>
                <span>Last Name</span>
            </li>
        </ul>
    </div>
</div>
</body>
</html>

main.js

function ngAddressListController($scope)
{
    $scope.contacts = [
        {first_name:'Jane', last_name:'Doe'},
        {first_name:'Jhon', last_name:'Doe'}
    ];
}

看起来有角度<1.3是,我应该坚持下去吗?

我不确定,但考虑到您在那里定义控制器(带有裸露的全局函数)的方法在AngularJS文档中一直存在到1.2.19,然后在1.2.20中消失了,我认为这种方法是不赞成的。

定义控制器的传统方法如下:

// define an app module
angular.module('myApp', [])
// add a controller to it
.controller('ngAddressListController', ['$scope', function ($scope) {
    $scope.contacts = [
        {first_name:'Jane', last_name:'Doe'},
        {first_name:'Jhon', last_name:'Doe'}
    ];
}]);

然后在你的HTML中,你会使用你的应用程序的名称:

<html ng-app="myApp">

从1.2.20版本开始,ngController文档的顶部就使用了这种风格。

https://docs.angularjs.org/guide/controller

另请参阅1.2.19文档中的注释:

注意:尽管Angular允许您在全局范围内创建控制器函数,但不建议这样做。在实际应用程序中,您应该使用角度模块的.controller方法进行应用程序,如下所示