J. Doe
J. Doe

Reputation: 3

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

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>

Upvotes: 0

Views: 411

Answers (2)

shreyansh
shreyansh

Reputation: 1687

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'}];

}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692181

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.

Upvotes: 1

Related Questions