ng-repeat angular中的shuffle数组

 古子同 发布于 2023-02-08 07:45

我正在创建一个测验,每次我开始测验时我想要改变问题,这样他们每次都不会出现在同一个顺序中.

我在我的HTML代码中有这个:

{{question.question}}
{{answer.answer}}

这在我的控制器中

 lycheeControllers.controller('quizCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('json/questions.json').success(function (data) {
        //all questions
        $scope.questions = data;

        $scope.titel = "Check your knowledge about lychees"


        $scope.randomSort = function(question) {
                      return Math.random();
                    };

        //filter for getting answers / question
        $scope.ids = function (question) {
            return question.id == number;
        }

        $scope.find = function (id) {
            if (id == number) {
                return true;
            }
        }


        $scope.next = function () {
            if (!(number == (data.length))) {
                //questionId++;
                number++;
                if (correct == true) {
                    points++;
                }
                //alert(points);
            } else {
                if (!end) {
                    if (correct == true) {
                        points++;
                        end = true;
                    }
                }

                alert("Quiz finished: your total score is: " + points);
            }
            correct = false;
        }

        $scope.checked = function (answer) {
            //alert(answer.answer);

            if (answer.correct == "yes") {
                correct = true;
            } else {
                correct = false;
            }

            //alert(correct);
        }


    });

}])
;

不幸的是,这根本不起作用.希望有人可以帮助我这个吗?

1 个回答
  • 谢谢 http://bost.ocks.org/mike/shuffle/ 使用这个改组函数:

    与它相关的是,输入数组保持可绑定,因为混洗不会创建新数组,而是在同一引用上进行混洗.

    // -> Fisher–Yates shuffle algorithm
    var shuffleArray = function(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;
    }
    

    旁注: lodash _.shuffle(array)不起作用,因为他们正在创建一个破坏绑定的新数组(因此一个混洗数组不会触发模型变脏)


    要完成工作解决方案的答案,请执行以下步骤:

    复制该功能,以便您可以在控制器内使用它.

    $http结果回调中调用它:

    $http.get('json/questions.json').success(function (data) {
      //all questions
      $scope.questions = data;
    
      shuffleArray($scope.questions);
    
      ...
    }
    

    2023-02-08 08:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有