如果其他条件在angularjs模板中

If else conditions in angularjs templates

本文关键字:angularjs 其他 条件 如果      更新时间:2024-02-01

我对AngularJs很陌生。我正在做一个问答;一个应用程序,我必须以表格的形式呈现一些问题及其答案。我有三种类型的问题,我必须用不同的方式回答。每个问题都分配了一个类型。如果question.type是"MCQ",则选项或答案应使用HTML复选框呈现,如果问题类型是NUM,则答案应使用单选按钮呈现。我尝试过这个,并在AngularJs模板中使用if条件。我的代码是

<table>
    <thead>
        <td>Questions</td>
        <td></td>
        <td>Hints</td>
    </thead>
    <tr data-ng-repeat="question in quizdata.questions">
        <td ng-if="question.type==MCQ">
            <li>{[{question.question_text}]}</li>
            <ol data-ng-repeat="answerswer in question.answers">
                <li>
                    <input type="checkbox">{[{answer.answer_text}]}</input> 
                </li>
            </ol>
        </td>
        <td ng-if="question.type==FIB">
            <ol data-ng-repeat="answerswer in question.answers">
                <li>
                    <input type="text"> </input>
                </li>
            </ol>
        </td>
        <td ng-if="question.type==NUM">
            <ol data-ng-repeat="answerswer in question.answers">
                <li>
                    <input type="radio">{[{answer.text}]}</input>
                </li>
            </ol>
        </td>
        <td></td>
        <td ng-if="quizdata.attempt_hint">
            {[{question.hint}]}
        </td>
    </tr>
</table>

我试过了。但我认为,如果条件没有得到执行。因为如果条件为false或true,它将在每种情况下呈现所有元素。我是否以正确的方式使用if条件?AngularJs模板中还有其他条件吗?我们将非常感谢您的帮助。

您要查找的是ngSwitch指令,它应该在处理互斥条件时使用:

<td ng-switch="question.type">
    <div ng-switch-when="MCQ">
      <li>{[{question.question_text}]}</li>
      <ol data-ng-repeat="answerswer in question.answers">
          <li>
              <input type="checkbox {[{answer.answer_text}]}</input> 
          </li>
      </ol>
    </div>
    <div ng-switch-when="FIB">
        <ol data-ng-repeat="answerswer in question.answers">
            <li>
                <input type="text"> </input>
            </li>
        </ol>
    </div>
    <div ng-switch-when="NUM">
        <ol data-ng-repeat="answerswer in question.answers">
            <li>
                <input type="radio">{[{answer.text}]}</input>
            </li>
        </ol>
     </div>
</td>
<td ng-if="quizdata.attempt_hint">
    {[{question.hint}]}
</td>

如果你确定要使用ngIf而不是ngSwitch作为@Blackhole引用,我只会确保你将question.type与字符串进行比较,而不是Angular可能解释为对象或其他变量的内容。

例如,代替:

<td ng-if="question.type==FIB">

用途:

<td ng-if="question.type == 'FIB'">

希望能有所帮助!