我有一个包含问题的 json 文件,所以是一个数组。我想让所有的问题都是随机的。这是我在 js 文件中的代码,但我不知道为什么不起作用。
$http.get('quiz_data.json').then(function(quizData){
$scope.myQuestions = quizData.data;
$scope.myQuestions = Math.floor(Math.random()*2);
});
在 html 中
<div ng-repeat="myQuestion in myQuestions">
<p class="txt">{{myQuestion.question}}</p></div>
最佳答案
使用:
$scope.randomQuestion= $scope.myQuestions[Math.floor(Math.random() * $scope.myQuestions.length)];
在 View 中: {{randomQuestion}}
更新:
$http.get('quiz_data.json').then(function(quizData){
$scope.myQuestions = quizData.data;
$scope.randomQuestion= $scope.myQuestions[Math.floor(Math.random() * $scope.myQuestions.length)];
});
HTML:
<div ng-repeat="myQuestion in myQuestions">
<p class="txt">{{randomQuestion.question}}</p></div>
最终更新:
因此,实际的问题不是随机化问题,而是打乱问题:
在你的js文件中:
function shuffleArray(array) {
var m = array.length,
t, i;
// While there remain elements to shuffle
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
// access the http service
// quizData object = data from quiz_data.json
$http.get('quiz_data.json').then(function(quizData) {
$scope.myQuestions = quizData.data;
$scope.totalQuestions = $scope.myQuestions.length;
shuffleArray($scope.myQuestions);
});
您的 HTML:
<div ng-repeat="myQuestion in myQuestions">
<p class="txt">{{myQuestion.question}} </p>
</div>
关于javascript - Angular JS中的随机函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35703248/