Working with conditional statements in AngularJS templates

As a beginner in AngularJs, I am currently developing a Q&A Application that requires rendering questions and their answers in a table format. The questions fall into three different types, each requiring a unique rendering style. Every question is associated with a type, such as "MCQ" for Multiple Choice Questions or "NUM" for numerical answers. When the question type is "MCQ," the options or answers should be displayed using HTML checkboxes, while for "NUM" questions, radio buttons should be used. I attempted to achieve this by utilizing if conditions within the AngularJs Template. Here is a snippet of my code:

<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>

While attempting this method, I encountered issues with the execution of if conditions. It seems that all elements are rendered regardless of whether the condition is true or false. Can anyone provide guidance on utilizing if conditions correctly in AngularJs Templates? Are there alternative conditions like an "else" statement available in AngularJs Templates? Any help would be greatly appreciated.

Answer №1

If you are searching for a solution, consider using the ngSwitch directive when working with conditions that are mutually exclusive:

<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>

Answer №2

If you are certain that you want to utilize ngIf instead of ngSwitch like @Blackhole mentioned, make sure to compare the question type to a string rather than something Angular may interpret as an object or different variable.

For instance, don't use:

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

Instead, go with:

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

I hope this suggestion proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating pages with query parameters in Ionic 4 through script

I am looking to transmit data to another page using Angular routing. In my app-routing.module file, I have defined the routes as follows: const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { pa ...

Exploring the utilization of functions beyond module exports

Striving to clearly communicate my intentions, please feel free to ask if anything is unclear. Within a file named www, I am configuring my socket as follows: var server = http.createServer(app); var io = require('socket.io')(server); require(& ...

Designing an accordion with the main content peeking out slightly before collapsing into place

Seeking assistance in creating an accordion that displays a snippet of content before collapsing. I'm facing difficulty starting this project. While a basic accordion is simple to implement, I am unsure how to show a portion of the content (such as t ...

Find and extract elements from a nested array within an object inside another object within an array of objects

I am working with an array of objects that looks like this: [ { likes: [], _id: 5f254e21fd3e040640de38b2, content: 'try this', author: { posts: [Array], comments: [], images: [], followers: [Array], ...

Is there a way to dynamically load a JSON configuration during runtime within a React application?

I am working on a React app that includes static content and does not use Node.js. I am in need of loading a configuration file in JSON format during runtime. The configuration file must be loaded in runtime because it needs to contain different data depe ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

How can I achieve super subtle shading effects in three.js?

Is there a way to achieve a very soft and subtle shadow in three.js, similar to the one in this image? https://i.sstatic.net/6B6en.jpg So far, I have only been able to create something like this: https://i.sstatic.net/a3rgD.png Here are my current light ...

Add a Time Stamp to the Ajax URL Query

I'm attempting to add a timestamp to my URL that is being called by AJAX every 5 seconds. The purpose is to prevent caching in Internet Explorer browsers. However, it seems like the AJAX call is not functioning properly now without any error messages. ...

the hidden input's value is null

I am encountering an issue with a hidden input in this form. When I submit the form to my API, the value of the input is empty. Isbn and packId are both properties of a book model. However, for some reason, the value of packId is coming out as empty. & ...

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

The responseText is displaying the contents at the beginning of my PHP script

I'm currently working on a project where I'm using ajax to fetch data from a database. My main focus right now is figuring out how to successfully send an array from the php file to the javascript function that handles my ajax requests. My curre ...

How can one efficiently copy portions of object arrays in JavaScript while maintaining elegance?

I have two sets of data. Set arrayOne consists of elements of type myObject1: var myObject1 = { Id: 1, //key params: { weight: 52, price: 100 }, name: "", role: "" }; Set arrayTwo consists of elements of type myObject2: var myObject2 = { I ...

What are the steps to resolving the issue of "Property does not exist on type 'Object' in Ionic 3"?

After calling the API to fetch data, I encountered the error message "Property sellerDto does not exist on type Object in ionic3". I tried declaring the data as an object, but the same error persists. How can I resolve this issue? /* @Copyright Notic ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...

Challenges with JQuery content sliders

I need some guidance in web development as I am new to it. My goal is to create a basic slider using JQuery, but I encountered an issue with slide3. It remains visible while moving across the screen when transitioning to left:0. I'm unsure of what wen ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list. array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", E ...

"Exploring the integration of video.js with React Hooks: A step-by-step

I have been utilizing video.js within the React framework and am now looking to transition to React Hooks. The current version of my React project is 16.8.3 Below is the initial functioning code: import React, { PureComponent } from 'react'; i ...

What is the best way to stop a jQuery function from applying titles extracted from the first row th's in thead's to multiple tables in a document?

My circumstances: I am new to jQuery and Stack Overflow, seeking assistance for my website project. The challenge: Building a website using Bootstrap 3.3.6 with intricate data tables that need to be stacked dynamically on mobile devices using CSS. It is c ...