Get answers for AngularJS ng-repeat by initializing inputs with the corresponding answer object

I have a set of questions coming from an AJAX response that I am displaying using ng-repeat. Each question input in the list needs to be connected to a separate answers array through its ng-model.

Here is an example of how the question array looks:

bookingQuestions: [
    0: {
        label: 'Any allergies?',
        type: 'text',
        id: 1234
    },
    1: {
        label: 'Names of attendees',
        type: 'text',
        id: 1235
    }
]

To handle this, I loop through all questions and create an answers array by assigning each question with its corresponding empty answerValue property. The structure of the answers array is as follows:

bookingAnswers: [
    0: {
        id: 1234,
        answerValue: ''
    },
    1: {
        id: 1235,
        answerValue: ''
    }
]

Within my markup, I am trying to initialize the answerObj variable by matching it with the correct answer object based on the respective question.

<div class="question" ng-repeat="question in bookingQuestions">
    <label class="question-label" for="{{question.id}}">{{question.label}}
    </label>
    <input type="text" name="{{question.id}}" ng-model="answerObj"
           ng-init="answerObj = getAnswerObj(question)">
</div>

The JavaScript function involved in retrieving the correct answer object is shown below:

$scope.getAnswerObj = function(question) {
    angular.forEach(bookingAnswers, function(answer) {
        if(question.id === answer.id) {
            return answer.answerValue;
        }
    });
}

Although the JavaScript function is successfully returning the desired object property, the ng-model is not getting updated accordingly. How can I resolve this issue?

Answer №1

To ensure consistency, you link the ng-model of all input fields to a common variable called answerObj. By utilizing $index, you are able to retrieve the current iteration's index. Therefore, you have the ability to implement something similar to the following:

<input type="text" name="{{question.id}}"
       ng-model="bookingAnswers[$index].answerValue"> </div>

Answer №2

<div class="question" ng-repeat="question in bookingQuestions">
    <label class="question-label" for="{{question.id}}">{{question.label}}
    </label>
    ̶<̶i̶n̶p̶u̶t̶ ̶t̶y̶p̶e̶=̶"̶t̶e̶x̶t̶"̶ ̶n̶a̶m̶e̶=̶"̶{̶{̶q̶u̶e̶s̶t̶i̶o̶n̶.̶i̶d̶}̶}̶"̶ ̶n̶g̶-̶m̶o̶d̶e̶l̶=̶"̶a̶n̶s̶w̶e̶r̶O̶b̶j̶"̶
    <input type="text" name="{{question.id}}" ng-model="answerObj.answerValue"
           ng-init="answerObj = getAnswerObj(question)" />
</div>
$scope.getAnswerObj = function(question) {
    angular.forEach(bookingAnswers, function(answer) {
        if(question.id === answer.id) {
            ̶r̶e̶t̶u̶r̶n̶ ̶a̶n̶s̶w̶e̶r̶.̶a̶n̶s̶w̶e̶r̶V̶a̶l̶u̶e̶;̶
            return answer;
        }
    });
}

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

Looking for assistance in grasping a complex Typescript function?

I recently stumbled upon this code snippet involving a filter callback function on an array. I'm feeling lost while trying to comprehend the purpose of this function and have been attempting to dissect it into smaller pieces for better understanding, ...

Utilizing a While Loop for SQL Queries in a Node.js Environment

So, I was attempting to iterate through an array using a while loop. I was able to successfully print a result from the SQL connection without the while loop, confirming that the query is working. However, when I tried to implement the same query within a ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

Navigating programmatically to another page in Next.js can be easily achieved by utilizing the useRouter hook

Following a post request to an external API, my goal is to navigate back to the homepage. While I am familiar with React, this is my first experience using Next.js. Here's the snippet of code: export default function New({genres}) { const createMovie ...

Issues with hover styles and transitions not being correctly applied to newly appended elements in Firefox

Utilizing an SVG as an interactive floor plan, I have implemented a feature where hovering over different areas on the floor plan (<g> elements) causes them to expand and float above other areas. The element scaling is triggered by CSS, but I use jQu ...

Convert the assignment of a.x=3 to the setter method a->setX(3) using the provided script

As I transition a portion of my code from JS to C++, I find the need to refactor direct instance variable assignments into setter methods: a.xx=3; to a->setXx(3); along with getter methods: ...a.xx... to ...a->getXx()... Currently, I am utilizing ...

Issues arise when using jQuery's ajax() method with processData set to false, as it still adds form data to the URL, among

Today, I am delving into the world of jQuery to enhance a form's functionality, particularly to interact with a MySQL database. Here is the form I am working with: <form class="loginform" id="loginform" name="loginform"> <input type="ema ...

Ways to execute a JavaScript function upon a button click instead of during the page load completion

I searched on Google but couldn't find the answer, so I'm asking here for help. In the attached screenshot located at the end, when the user clicks on the download button, some backend actions are performed such as file transfer. Once the proces ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Combining NPM Script Commands: A Comprehensive Guide

I am aware that NPM scripts can be chained using &&, pre-, and post- hooks. However, I am wondering if there is a way to simply break down lengthy script lines into a single, concatenated line? For instance, can I convert the following: "script": ...

Tips for changing the functionality of ng-click:

Is there a way to make a form button switch from saying Save to Saving... when it's busy? It would be great if this functionality could detect the presence of an ng-click directive and only execute that directive if busy is set to false. Do I need to ...

Employing JSON within an MVC 5 controller function

var checkboxes = $("input[type='checkbox']"); $(function () { function getCheckedValues() { /* declare an array to store the checked values */ var chkArray = []; /* look for all checkboxes that have a class 'chk& ...

How about a fading effect for the select box?

I'm currently working on creating a select tag that opens its options slowly with a fade in, fade out effect when the user clicks on "Actions." I've attempted to use jQuery for this feature but haven't had any luck. Here's my code: &l ...

Keep an ear out for updates on object changes in Angular

One of my challenges involves a form that directly updates an object in the following manner: component.html <input type="text" [(ngModel)]="user.name" /> <input type="text" [(ngModel)]="user.surname" /> <input type="text" [(ngModel)]="use ...

When you neglect to include 'window' in your Angular expressions, you may encounter the error message "Window referencing is prohibited!"

Switching from AngularJS v1.2.17 to v1.2.28 brought about a surprise - one of my pages started throwing JavaScript errors, specifically: Error: [$parse:isecwindow] Referencing the Window in Angular expressions is disallowed! Expression: model.skAccoun ...

Using an AJAX post request will result in receiving an HTML element, especially when an attachment is included with Paperclip

I've created an innovative application where users can share their stories through ajax submissions and engage with other readers by commenting on the stories using ajax as well. The technology stack I'm working with includes Rails 3.0.3, ruby 1. ...

Generate steps using Material UI/React Stepper to create organized pages (similar to Table Pagination)

As I venture into using Material UI along with React, my goal is to create organized "pages" consisting of steps in sets of four for a specific process. My initial attempt displayed all 10 steps on a single view, despite having the pagination correctly ca ...

Enhance your code's readability with the Code Beautifier Tool for improved clarity

I recently came across a website where they intricately formatted their code with line numbers and highlighting, but I couldn't find any information on how to achieve this effect. I want my code to look just like that, can anyone help me out? Website ...

Display a persistent bar on the page until the user reaches a specified <div> element through scrolling

Looking to implement a sticky bar at the bottom of my page that fades out once the user scrolls to a specific div and then fades back in when scrolling up and the div is out of view. This bar should only appear if the user's screen size is not large ...