1

我有一个对象数组,每个对象都包含一个字符串数组。我正在使用 ng-repeat 列出所有字符串,并有一个按钮可以更改为下一组字符串(通过更改最外层数组中选择的对象)。这是我的代码

HTML

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="quizRadioButton.css"/>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="quizAngularJs.js"></script>
<title>American History Quiz</title>
</head>
<body ng-app="myApp">
    <div ng-controller="questionCtrl">
        <form>
            <h1>{{question}}</h1>
                <ul>
                    <li ng-repeat="choice in choices"><input type="radio" name = "answer">{{choice}}</li>
                    <li>{{count}}</li>
                </ul>
            <button ng-click= "upCount()">Submit Form</button>
            <button id='goBack'>Go Back</button>
        </form>
    </div>
</body>

和 Javascript

var myApp = angular.module('myApp', []);

function questionCtrl($scope){
var allQuestions = [....];
$scope.count = 0;
$scope.question = allQuestions[$scope.count].question;
$scope.choices = allQuestions[$scope.count].choices;

$scope.upCount = function(){
    $scope.count = $scope.count + 1;
};
}    

数组中的每个对象看起来像这样

{
 question: "question A",
 choices: ["choice 1", "choice 2", "choice 3"],
 correct answer: 0
}

我确实检查以确保计数正在更新,并且确实如此。如果计数正在更新,视图不应该随之更新吗?我也为我的功能尝试过这个,但仍然无法让它工作。

$scope.upCount = function(){
    $scope.count = $scope.count + 1;
    $scope.question = allQuestions[$scope.count].question;
    $scope.choices = allQuestions[$scope.count].choices;
};

谢谢您的帮助

4

1 回答 1

0

您可以简单地将所有问题放在范围内。我认为您不需要两个单独的模块来跟踪当前问题。单独计数应该可以达到目的。

var myApp = angular.module('myApp', []);
function questionCtrl($scope){
    $scope.allQuestions = [....];
    $scope.count = 0;
    $scope.upCount = function(){
        /* make sure index don't run out of range */
        if($scope.allQuestions[$scope.count + 1])
            $scope.count = $scope.count + 1;
    };
    $scope.upCount = function(){
        /* make sure index don't run out of range */
        if($scope.allQuestions[$scope.count - 1])
            $scope.count = $scope.count - 1;
    };
}    

然后在您的 HTML 中,您可以简单地执行以下操作:

<body ng-app="myApp">
    <div ng-controller="questionCtrl">
        <form>
            <h1>{{allQuestions[count].question}}</h1>
            <ul>
                <li ng-repeat="choice in allQuestions[count].choices">
                    <input type="radio" name = "answer">{{choice}}</li>
                <li>{{count}}</li>
            </ul>
            <button ng-click= "upCount()">Submit Form</button>
            <button id='goBack'>Go Back</button>
        </form>
    </div>
</body>
于 2013-08-10T08:07:45.953 回答