如果在angularjs模板中有条件

Saj*_*mad 12 javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我对AngularJs很新.我正在制作一个Q&A应用程序,我必须以表格的形式提出一些问题和答案.我有三种类型的问题,我必须以不同的方式呈现.每个问题都有一个分配的类型.如果question.type是"MCQ",则选项或其答案应使用HTML复选框呈现,如果问题类型为NUM,则应使用单选按钮呈现其答案.我试过这个并使用AngularJs模板中的条件.我的代码是

<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="answer in question.answers">
                <li>
                    <input type="checkbox">{[{answer.answer_text}]}</input> 
                </li>
            </ol>
        </td>

        <td ng-if="question.type==FIB">
            <ol data-ng-repeat="answer in question.answers">
                <li>
                    <input type="text"> </input>
                </li>
            </ol>
        </td>

        <td ng-if="question.type==NUM">
            <ol data-ng-repeat="answer 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>
Run Code Online (Sandbox Code Playgroud)

我试过这样的.但我认为如果条件没有执行.因为如果条件为false或true,它会渲染每种情况下的所有元素.我是否以正确的方式使用if条件?AngularJs模板中还有其他条件吗?帮助将受到高度赞赏.

Bla*_*ole 23

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

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


jmd*_*mdb 9

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

例如,而不是:

<td ng-if="question.type==FIB">
Run Code Online (Sandbox Code Playgroud)

使用:

<td ng-if="question.type == 'FIB'">
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

  • 没问题!乐于帮助.任何upvotes /已解决的学分表示赞赏! (2认同)