在JSON中改变对象(AngularJS)
问题描述:
我想让我的问题以随机顺序显示。我做到了,但它不能正常工作,有时没有遍历所有对象和停止等在JSON中改变对象(AngularJS)
$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
答
在move
方法,你可以超出阵列的范围。使其环绕,如果你的最后一个问题之前,首先或后移至:
$scope.currentQ = $scope.allData[(position + direction + $scope.allData.length) % $scope.allData.length];
你能解释一步你只是做一步,其实这部分“%$ scope.allData.length”?顺便说一下,它效果很好,所以感谢解决方案。你能帮我多做一件事,我在我的“quizController” - 倒数计时器中评论过一部分内容。它不能像它那样工作,你能给我一些关于这方面的建议吗? – ovesyan19 2015-02-07 18:35:08
@Alik:'%'模运算符返回第二个操作数的除法提醒。这种情况下的效果是,当索引在数组外部增长时,它从零开始回绕。括号内增加的长度是确保如果您用-1方向调用该函数,该值不会为负值。当你从'setTimeout'调用'countDowner'时,它将被调用为常规函数,而不是'$ scope'对象的方法。使用'$ timeout(function(){$ scope.countDowner();},1000);'将其称为方法。 – Guffa 2015-02-07 18:48:46
非常感谢,现在都变得清晰了。 – ovesyan19 2015-02-07 18:54:51