javascript - Angular JS中的随机函数

标签 javascript angularjs

我有一个包含问题的 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/

相关文章:

JavaScript 禁用选择选项

javascript - jQuery UI 相对于两个元素的位置

javascript - Chrome/Opera 闪烁绘画问题

css - 如何在angularjs中有一个图像占位符

javascript - MATH 恢复旋转坐标

javascript - 代码重复太多

javascript - Angular Directive(指令)和 ng 类

javascript - 使用一个指令从另一个隔离作用域复制作用域属性

ruby-on-rails - Rails + Angular + sqlite3部署

AngularJS 和摘要式 HTTP 身份验证