在JSON中改组对象(AngularJS)

时间:2015-02-07 18:18:43

标签: json angularjs html5 random

我希望我的问题以随机顺序显示。我做到了,但它没有正常工作,有时它不会遍历所有对象和停止等等。

 $scope.move = function (direction) {
    var position = $scope.allData.indexOf($scope.currentQ);
    $scope.currentQ = $scope.allData[position + direction];
};

$http.get("js/json/questions.json").then(function(response){
    $scope.allData = response.data;
    $scope.currentQ = $scope.allData[Math.floor(Math.random() * response.data.length)];
});

$scope.answerClick = function(index){
    $scope.clicks++;

    if(index === $scope.currentQ.answer){
        $scope.score++;
        $scope.rightwrong = "Right";
        $('.right-wrong').css("color", "green");
    }
    else{
        $scope.rightwrong = "Wrong";
        $('.right-wrong').css("color", "red");
    }

    if($scope.clicks === 4){
        resultService.score = $scope.score;
        $location.path('/finish');
    }

    $scope.move(+1);
};

以下是整个应用:http://plnkr.co/edit/wTQHOz

1 个答案:

答案 0 :(得分:0)

move方法中,您可以超出数组的范围。如果您在第一个问题之前或之后移动,请将其环绕:

$scope.currentQ = $scope.allData[(position + direction + $scope.allData.length) % $scope.allData.length];