我有一个对象数组,每个对象都包含一个字符串数组。我使用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;
};
感谢的帮助
您只需在范围内设置allQuestions即可。我认为你不需要两个单独的模块来跟踪当前的问题计数本身就应该达到目的。
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>