Angular JS中的随机函数

dra*_*gon 1 javascript angularjs

我有一个带有问题的json文件,所以是一个数组.我想让所有问题都是随机的.这是我的js文件代码,但我不知道为什么不起作用.

$http.get('quiz_data.json').then(function(quizData){
        $scope.myQuestions = quizData.data;
        $scope.myQuestions = Math.floor(Math.random()*2);
    });
Run Code Online (Sandbox Code Playgroud)

并在HTML中

<div ng-repeat="myQuestion in myQuestions"> <p class="txt">{{myQuestion.question}}</p></div>

Sun*_*ama 5

使用:

$scope.randomQuestion= $scope.myQuestions[Math.floor(Math.random() * $scope.myQuestions.length)];  
Run Code Online (Sandbox Code Playgroud)

在视图中: {{randomQuestion}}

更新:

$http.get('quiz_data.json').then(function(quizData){
        $scope.myQuestions = quizData.data;
        $scope.randomQuestion= $scope.myQuestions[Math.floor(Math.random() * $scope.myQuestions.length)];  
    });  
Run Code Online (Sandbox Code Playgroud)

HTML:

<div ng-repeat="myQuestion in myQuestions">
<p class="txt">{{randomQuestion.question}}</p></div>    
Run Code Online (Sandbox Code Playgroud)

最终更新:

所以,实际的问题不是随机化而是改变问题:

在你的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);
});  
Run Code Online (Sandbox Code Playgroud)

你的HTML:

<div ng-repeat="myQuestion in myQuestions">
    <p class="txt">{{myQuestion.question}} </p>  
</div>
Run Code Online (Sandbox Code Playgroud)