JavaScript错误在函数

时间:2017-09-20 10:02:40

标签: javascript jquery angularjs

我正在尝试使用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:$ scope.nextQuestion期望的对象   (http://localhost:63758/Scripts/app/quiz-controller.js:21:9)at   匿名功能   (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>

1 个答案:

答案 0 :(得分:3)

您正在注入$scope$http - 您应该为两者添加占位符:

myApp.controller('QuizController', ['$scope', '$http', function ($scope, $http) {
 ...
});