问题
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