0

我一直在做一个 angularjs 项目并遇到了一个我似乎无法解决的问题。问题是我有一个控制器,它有一个代表几个考试的数组。

function ExamCtrl($scope) {
    $scope.exams = [{
        "title" : "Some fancy title",
        "owner" : "John Smith",
        "questions" : [
            {"type" : "openquestion", "question" : "Is cheese yummy?", "answer" : "Yes"},
            {"type" : "mcquestion", "question" : "Is cheese yummy?", "answers" : [{"a" : "Yes"}, {"b" : "No"}]}
        ]
    }];
} 

就像你可以看到考试对象中有一个数组,其中包含几个问题对象。这些对象中的每一个都有不同的模式(openquestion、mcquestion 等)。我可以保证每个具有特定问题类型的对象都具有相同的架构。

我面临的问题是呈现属于每个问题类型的正确 HTML。在他们使用的 angularjs 网页的教程中

<li ng-repeat="question in exams.questions>{{question.type}}</li>

这种方法的问题是我无法区分不同的问题类型。我一直在尝试用指令来解决这个问题,并且一直在与编译和链接函数进行激烈的斗争,但一直未能找到一个好的解决方案。

4

1 回答 1

0

好吧,这是一个工作小提琴

我对您的考试模型结构所做的较大更改之一是我将“答案”设为字典对象而不是数组,并且在所有 questionType 案例中,我将实际选择的答案存储在 question.answer 中。

我猜这个标记有点棘手:

    <ul ng-repeat="exam in exams">
        <li ng-repeat="question in exam.questions">
            <p>{{question.question}}</p>
            <div ng-switch on="question.type" >
                <div ng-switch-when="openquestion">
                    <textarea ng-model="question.answer"></textarea>                        
                </div>
                <ul ng-switch-when="mcquestion">
                    <li ng-repeat="(key, value) in question.answers">
                        <label>
                        <input ng-model="$parent.question.answer" value="{{value}}" type="radio"/>
                            {{key}} ) {{value}}
                        </label>
                    </li>                        
                </ul>
              </div>
        </li>
    </ul>

这是它背后的JS:

app.controller('MainCtrl', function($scope) {
   $scope.exams = [{
        "title" : "Some fancy title",
        "owner" : "John Smith",
        "questions" : [
            {"type" : "openquestion", "question" : "Is cheese yummy?", "answer" : "Yes"},
            {"type" : "mcquestion", "question" : "Is cheese yummy?", "answers" : { a: "Yes", b: "No" }, "answer" : "No"}
        ]
    }];
});

​</p>

我希望这会有所帮助。

于 2012-12-04T22:02:13.343 回答