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

邮差的信 提交于 2019-12-12 01:53:45

问题


I'm trying to make my first controller and getting this error:

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

I've simplified my code to find the error but no luck. It looks to my like I'm creating the controller and the books array in the script and referencing the controller letter by letter in the div. What am I missing?

<!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>

回答1:


It's been a very long time since global functions aren't controllers anymore in angular.js. You need to register the function as a controller in your module:

<html ng-app="myApp">

and in the JS code:

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

Your angular knowledge is out-of-date. re-read the documentation.




回答2:


or the more simplified way

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

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

}


来源:https://stackoverflow.com/questions/36205895/angularjs-error-ngareq-argument-testcontroller-is-not-a-function-got-unde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!