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.