Verify whether the items within the ng-repeat directive already contain the specified value

I am facing an issue with displaying a JSON string of questions and answers in ng-repeat. The problem is that I want to display each question only once, but show all the multiple answers within ng-repeat.

{Answer:"White",AnswerID:967,answer_type:"RADIO",fullquestion:"Your Race",id:6}{Answer:"African American",AnswerID:968,answer_type:"RADIO",fullquestion:"Your Race",id:6}{Answer:"Asian",AnswerID:969,answer_type:"RADIO",fullquestion:"Your Race",id:6}

The current view I have set up is as follows:

 <div ng-repeat="hrq in HrqQuestions">
            <div class="list card normal">
                <div class="item item-body item-divider">                    
                    <p ng-bind="hrq.fullquestion"></p>                       
                </div>
                <label class="item item-input" ng-show="hrq.answer_type=='FREETEXT'">
                    <input ng-model="hrq.Answer" name="name" type="text">
                </label>
                <div ng-if="hrq.answer_type=='RADIO'">
                    <ion-radio ng-click="selectedAnswer(hrq.AnswerID,hrq.Answer)" name="radio1" ng-value="hrq.AnswerID">{{hrq.Answer}}</ion-radio>
                </div>
            </div>
        </div>

Currently, the questions are being repeated multiple times with different answers, like:

     Q.Your Race
           White Your Race
     Q.Your Race
           African American Your Race
     Q.Your Race
           Asian

However, what I need is:

     Q. Your Race
           White 
           African American  
           Asian

If anyone can help me achieve this structure, I would greatly appreciate it.

Answer №1

Here is a suggestion:

  1. Make sure to set your 'HrqQuestions' variable as an array
  2. Group your questions based on their unique 'id' values
  3. Repeat the same values for grouped questions

angular.module('app',['angular.filter']).controller('MainController', function($scope) {
  $scope.HrqQuestions = [
      {Answer:"White",AnswerID:967,answer_type:"RADIO",fullquestion:"Your Race",id:6},
      {Answer:"African American",AnswerID:968,answer_type:"RADIO",fullquestion:"Your Race",id:6},
      {Answer:"Asian",AnswerID:969,answer_type:"RADIO",fullquestion:"Your Race",id:6}
    ];
 });
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js"></script>

<body ng-controller="MainController">
  <div ng-repeat="(key, value) in HrqQuestions | groupBy: 'id'">
    <div><strong>Id:</strong> {{ key }}</div>
     <p ng-repeat="v in value">
       <strong>Answer {{ $index + 1}}</strong>. {{ v.Answer }}
     </p>
  </div>
</body>
</html>

Answer №2

For a demonstration, check out this fiddle

    <div ng-controller="MyCtrl">      
  <div ng-repeat="hrq in HrqQuestions">
            <div class="list card normal">
                <div class="item item-body item-divider">                    
                  <p>{{$index + 1}}. {{hrq.fullquestion}}</p>              
                </div>
                <div ng-repeat="answer in hrq.answers">
                  <label class="item item-input" ng-show="answer.answer_type=='FREETEXT'">
                    <input ng-model="answer.Answer" name="name" type="text">
                </label>
                <div ng-if="answer.answer_type=='RADIO'">
                    <input type="radio" ng-click="selectedAnswer(answer.AnswerID,answer.Answer)" name="radio1" ng-value="answer.AnswerID">{{answer.Answer}} 
                </div>
                </div>
                <br>
            </div>
        </div>
</div>

Here is the controller code:

    $scope.HrqQuestions = [{ fullquestion: "Your Race", id: 6,
                         answers: [{ Answer: "White", AnswerID: 967, answer_type: "RADIO" },
                                   { Answer: "African American", AnswerID: 968, answer_type: "RADIO" },
                                   { Answer: "Asian", AnswerID: 969, answer_type: "RADIO" }] }, 
                        { fullquestion: "My Race", id: 7, 
                          answers: [{ Answer: "Black", AnswerID: 967, answer_type: "RADIO" },
                                    { Answer: "African Indian", AnswerID: 968, answer_type: "RADIO" },
                                    { Answer: "India", AnswerID: 969, answer_type: "RADIO" }] }];

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

Tips on allowing a rectangle to be draggable using HTML5

I have been experimenting with resizable and draggable rectangles in HTML5. I've managed to create resizable rectangles, but I am having trouble getting them to drag using mouse events. You can view my JSFiddle code at the following link: here. / ...

Check for compatibility of overflow:scroll with mobile browsers

Is there an easy JavaScript method that works across different devices and libraries? I am looking to assign a class to the html element in order to enable scrollable containers on mobile devices when needed. I want to follow a similar approach to Modern ...

Having trouble getting the if statement to run with JavaScript Closures?

Check out this code snippet: let url = URL; let imageURL = ''; $.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post", function (data) { let json_data = JSON.stringify(data); json_data ...

Combine several items to form a single entity

When I have two objects returned from the database, my goal is to combine them into one object. Here are the examples: { "id": 4, "first_name": "s", "last_name": "a", ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

JavaScript: Only a single function call is successful

Recently, I encountered an issue with my registration form. Everything was working smoothly until I attempted to add a new onblur() event to a different text field within the same form. Surprisingly, this caused the original ajax call to stop functioning, ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Error while retrieving reference from mongoDB in NodeJS

I am currently working on a small website that needs to query my local mongodb. Everything works perfectly fine on localhost. That's why I decided to begin with NodeJS. While all JavaScript functions work seamlessly when run separately, I encounter a ...

There seems to be an issue with declaring Gulp Open

Here is the code snippet for my `open.js` task: import gulp from 'gulp'; import gulpOpen from 'gulp-open'; gulp.task('open', () => { // doesn't work with `function()` either. const options = { uri: 'local ...

I'm attempting to make this script function correctly when an image is loaded

Can anyone help me figure out how to make this script function on image load instead of onclick? I came across the script on stackoverflow, but it was originally set up for onclick. I want it to work for onload or .load HTML====== <div id="contai ...

Tips for safely storing JWT tokens in a react/next.js app:

After a valid user login following proper registration through REST API, I am looking for the best way to store the JWT token that is generated. I have researched various methods of storing JWT on the client side, including local storage, session storage, ...

Encountering status code 0 when handling 413 (Request Entity Too Large) error in AngularJS with Loopback API

1. Revealing Some Details In my client-side application built with AngularJS 1.3.15, I am utilizing a loopback API for handling requests. Within the application, I have set up interceptors using $httpProvider.interceptors to interpret status codes and di ...

Scope binding is successful, but accessing the array is only possible after adding an Alert() function

Within my Angular controller, I'm utilizing the SharePoint JavaScript Object Model to fetch data from the Taxonomy (term store). Due to SharePoint's JSOM not being a conventional Angular function that can be easily understood by the scope, I util ...

Present the retrieved JSON data values in an alternative layout on the table

I am facing an issue with the data display in my current table setup. The data is fetched from an SQL server, encoded into JSON format, and the structure of the JSON output is causing a problem for me. You can see how it looks like here: The challenge I a ...

The onClick functionality for the IconComponent (dropdown-arrow) in React Material UI is not functioning properly when selecting

I have encountered a problem in my code snippet. The issue arises when I attempt to open the Select component by clicking on IconComponent(dropdown-arrow). <Select IconComponent={() => ( <ExpandMore className="dropdown-arrow" /> )} ...

What are the steps to create an endless scrolling feature?

I'm trying to create a slider with a horizontal scrolling effect, but I've hit a roadblock. How can I make the slider scroll infinitely? In my code, you can see that after Item 6, it stops scrolling and I have to scroll backward. However, I want ...

What is the process for removing a specific row from a datatable?

I have implemented a data-table using Vue and Vuetify. When I click on the delete icon in a specific row, a snackbar pops up with two buttons - yes and no. If I click on the yes button, I want to delete that specific row. How can I achieve this functionali ...

The interlocking web of Angular dependencies

Can I begin my angular module without specific dependencies? This is my angular.module. angular.module("app", [ 'ngSanitize', 'ngAnimate', 'ui.router', 'ngMaterial', 'ngRoute', 'ngCookies', &a ...

Verify the accuracy of quiz responses with PHP and AJAX

I am working on a picture quiz that has one input field for each image. I am looking for a solution to verify if the value entered into the input field matches the correct answer. If it does match, I need to perform certain operations like adding or removi ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...