我正在尝试使用 VS2015、JavaScript、Angular、MVC 5 构建应用。
这是我的 JavaScript 代码:
var myApp = angular.module('QuizApp', []);
myApp.controller('QuizController', ['$scope', function ($scope, $http) {
$scope.answered = false;
$scope.title = "loading question...";
$scope.options = [];
$scope.correctAnswer = false;
$scope.working = false;
$scope.answer = function () {
return $scope.correctAnswer ? 'correct' : 'incorrect';
};
$scope.nextQuestion = function () {
$scope.working = true;
$scope.answered = false;
$scope.title = "loading question...";
$scope.options = [];
$http({
method: 'GET', url: "/api/trivia"
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.options = data.options;
$scope.title = data.title;
$scope.answered = false;
$scope.working = false;
}, function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.title = "Oops... something went wrong";
$scope.working = false;
});
};
$scope.sendAnswer = function (option) {
$scope.working = true;
$scope.answered = true;
$http({
method: 'POST',
url: "/api/trivia",
data: { 'questionId': option.questionId, 'optionId': option.id }
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.correctAnswer = (data === true);
$scope.working = false;
}, function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.title = "Oops... something went wrong";
$scope.working = false;
});
}
}]);
当我尝试运行它时,出现此错误:
TypeError: Object expected at $scope.nextQuestion (http://localhost:63758/Scripts/app/quiz-controller.js:21:9) at Anonymous function (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js:176:498) angular.js (10061,11)
这里是我使用函数 nextQuestion() 的地方:
<div class="flip-container text-center col-md-12" ng-controller="QuizController" ng-init="nextQuestion()">
......
</div>
最佳答案
您正在注入(inject) $scope
和 $http
- 两者都应该有占位符:
myApp.controller('QuizController', ['$scope', '$http', function ($scope, $http) {
...
});
关于函数预期的 JavaScript 错误对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46319064/