Implementing conditional removal of nested partial in AngularJS repeat loop

Question:

Is there a way to utilize ng-repeat in Angular to eliminate nested items inside the ng-repeat item based on certain conditions, while keeping the ng-repeat item itself intact? Simply hiding the item is not sufficient - it needs to be fully removed. I'm still learning the ropes when it comes to Angular.

Detailed Background/My Attempts:

I am currently working on a project that involves transitioning to Angular from a mix of various technologies. In this project, there is a form generated based on the response received from a REST service. The service provides a JSON response structured like so:

{
   "questions": [{
       "type": "multiplechoice",
       "question": "how are you?",
       "answers": [{
          "text": "bad",
          "value": 0
       }, {
          "text": "good",
          "value": 1
       }]
   }, {
       "type": "text",
       "question": "write a word"
   }, {
       "type": "date",
       "question": "pick a date"
   }]
}

Depending on the type of question, HTML is dynamically created in JavaScript and added to the DOM. Given our collaborative workflow where multiple team members can modify the HTML without getting involved in other technical aspects, I felt it would be better not to include HTML within JavaScript (among other considerations). Instead, I proposed using a static HTML template that could be populated with the response at runtime but remain present on the page even without the service active for easy editing.

<div class="multiplechoice">
    <label><input type="checkbox" value="{{question.value}}"> {{question.text}}</label>
</div>

<div class="text">
    <input type="text">
</div>

<div class="date">
    <input type="date">
</div>

This approach allows team members to edit the HTML template directly since it's visible on the live page. Subsequently, JavaScript can duplicate the relevant divs and fill them with appropriate content by repeating or setting values as needed.

My query revolves around finding the most effective method to achieve this functionality in Angular. After experimenting with different techniques, I settled on the following structure:

<li ng-repeat="question in questions" class="{{question.type}}">
    <div class="multiplechoice">
        <label ng-repeat="q in question.answers"><input type="checkbox" value="{{value}}"> {{text}}</label>
    </div>
    <div class="text">
        <input type="text">
    </div>
    <div class="date">
        <input type="date">
    </div>
</li>

By utilizing CSS classes, I can show/hide elements based on their class names. For instance:

.date .date { display: block; }

Ultimately, my goal is to ensure that no unused templates or partials remain inside the list items once ng-repeat has completed its iteration. Therefore, if it's a date question, I would ideally want to see:

<li><input type="date"></li>

so that we can have a clean DOM traversal process.

Answer №1

If you want to improve readability, consider using ng-if or ng-show in your AngularJS code.

Instead of typing out

<div class='text' ng-if="question.type == 'text'">

try something like this:

<div class='text' ng-if="isText(question)">

Then, in your scope:

 $scope.isText = function(question){
       if(question.type == 'text'){
           return true;
       }else{
          return false;
       }
 }

This makes the code a bit easier to understand in your HTML.

Additionally, if you have more than two types, consider using ng-switch.

For more information, check out:

ng-switch :

ng-if: http://docs.angularjs.org/api/ng.directive:ngIf

ng-show : http://docs.angularjs.org/api/ng.directive:ngShow

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

Ways to divide a group of arrays within ng-repeat

I am new to Angular and currently facing an issue where I need to split Class Subjects into two columns named subject ID and Name using the delimiters "--" and ";". However, I am unsure how to achieve this within a table generated by ng-repeat. The curren ...

Is your Joomla table experiencing resizing issues?

I am currently working with Joomla to build a basic website. I installed the Form Maker Lite survey extension by Joomla Extension Survey for creating surveys and questionnaires. After publishing the extension on my Joomla site, I encountered an issue tryi ...

JSON error: Encountered an unexpected token "o" while processing

My database table: TABLE `events` ( `event_id` INT(11) unsigned NOT NULL AUTO_INCREMENT, `event_title` VARCHAR(255) NOT NULL, `event_desc` TEXT, `event_location` VARCHAR(255) NOT NULL, `event_requirements` TEXT DEFAULT NULL, `event ...

Exploring the World of Node.js Event Handling in JavaScript

After reviewing the provided code snippet: binaryServer = BinaryServer({port: 9001}); binaryServer.on('connection', function(client) { console.log("new connection"); client.on('stream', function(stream, meta) { console.log(& ...

Transforming this Rails form into an Ajax/JavaScript/jQuery format will eliminate the need for submission

I have developed a form in Rails that computes the Gross Profit Margin Percentage based on an input of Price. When a user selects the relevant product on the form and enters a price in the 'deal_price' field. A callback is triggered to retrieve ...

Error code 0 occurs in jQuery AJAX when there is an issue with the communication between the client

Currently delving into the world of ASP.NET and wanted to create a basic website utilizing ajax to retrieve a simple string from the server. Upon running the ajax request, an error message pops up stating An error occurred: 0 error Here's a glimpse ...

How to import a JSON file in AngularJS using Node.js

I am currently working with NodeJS and AngularJS to handle some data. Within my Angular application, I am trying to access a JSON file and distribute its content into separate controllers. Right now, I am utilizing the http.get method within a controller ...

Setting minimum or maximum dates in jquery-simple-datetimepicker is proving to be challenging

Currently, I am utilizing the following library: In this jsfiddle example: http://jsfiddle.net/3SNEq/2/, everything works perfectly when setting minDate or MaxDate directly in the appendDtpicker method. However, when trying to use handleDtpicker like thi ...

Enhance your queries with Mongoose: optimizing the find() and count() functions

Context An issue I am facing involves a Mongoose query that retrieves a set of objects and also provides the total count of those objects: var itemsPerPage = 4, pageNum = 1; Survey.find({}) .limit(itemsPerPage) .skip(itemsPerPage * pageNum) ...

The absence of button.onclick=func in the HTML code is notable

I am facing an issue where adding an onclick attribute to an input element via JavaScript does not display in the HTML, but the function gets executed. On the other hand, when I add the input element directly in the HTML code, the onclick attribute shows u ...

I am looking to extract the information from the HTML code

I have the following code and I need to extract the backupURL value. Can someone help me with this? var tem="<li><a class="selectBackupFromList" backupURL="http://localhost/3/wordpress/wp-content/infinitewp/backups/localhost-3-wordpress_installCl ...

The connection timed out when attempting to send a POST request from the client side to the API

After setting up a basic https response to send JSON data from the client to an API endpoint named /api on my a2 web server, I encountered an issue where the connection was being refused and no logs were appearing in the terminal accessed through SSH. The ...

Steps for displaying an image link on an aspx webpage

Is it possible to have the full-size image open on http//example.com/image.aspx when the thumbnail is clicked, instead of http//example.com/images/image.jpeg? I am looking for a solution that does not require creating individual pages for each image or edi ...

How to perform a table filtration in AngularJS with a focus on specific table columns

While conducting a search within my table data, I need to implement a filter that only targets a specific field at times. For instance, imagine a table with columns for number, name, and content. When entering text into the search box, I want it to search ...

Guide on sending data to MongoDB using Postman

I am currently facing an issue while trying to send data to the MongoDB database using Postman. Despite everything seeming fine, I keep encountering errors. https://i.stack.imgur.com/Gcf5Q.jpg https://i.stack.imgur.com/ntjwu.jpg https://i.stack.imgur.co ...

What are the steps to create a responsive Coin Slider?

Once the slider is generated, it appears that there is no built-in method to resize it, causing issues with responsive design. Is there a way to adjust the size of the Coin Slider plugin based on the media queries in Twitter Bootstrap 3? Take a look at C ...

Encountering a TypeError message stating that "selector.includes is not a function" while attempting to scrape using cheerio and

Trying my hand at web scraping with the code snippet below: const cheerio = require('cheerio'); const jsonframe = require('jsonframe-cheerio'); const $ = cheerio.load('https://coinmarketcap.com/all/views/all/'); jsonframe($) ...

The error message "Unable to access property 'x' of undefined" is appearing in the photoswipe js

There is an error in the library when using photoswipe.min.js: "Uncaught TypeError: Cannot read property 'x' of undefined" The code for myPhotoswipe is identical to the one on the official site: var initPhotoSwipeFromDOM = function(gallerySelec ...

Use CSS and HTML to ensure that all elements on the website are centered

I'm struggling to create a perfectly centered website layout. Let me share my CSS code with you: body { background-image: url('background.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...