Retrieving Data from a Form in AngularJS

Currently, I am working on a project where I am using 3 nested ng-repeat to read a JSON file and display various questions along with their answers. Everything seems to be working fine up to this point, but I am facing an issue with storing the selected answers and sending them to the API. For some reason, the selected answers are not being stored.

Below is a snippet of my view:

<form>
    <div class="panel panel-default" ng-repeat="section in questionsTest">
        <div class="panel-heading">
            <h1>{{ section.name }}</h1>
            <h3 class="panel-title">{{ section.name }}. {{
                section.description }}</h3>
        </div>
        <div class="panel-body" ng-repeat="question in section.questions">
            {{ question.statement }}
            <div ng-repeat="answer in question.answers">
                <label class="radio-inline"> <input type="{{ answer.type }}" ng-model="question.valor"
                    name="{{ question.id }}" id="{{ answer.id }}" value="{{ answer.id }}">
                    {{ answer.valor }}
                </label>
            </div>
        </div>
    </div>
</form>

And here is a snippet of the controller:

$scope.question = {};
$scope.testing = function(){
    console.log($scope.question);
};

The $scope.testing function is used for testing purposes to view the value of $scope.question in the console.

Answer №1

Your HTML structure appears to be correct, but it seems like you are not properly retrieving the selected values. To access the selected answer for the first question, you can use the following code snippet:

$scope.json.section[0].questions[0].value

The reason for this is that when you use question.valor in the ng-model, it corresponds to the n-th question within the n-th section. The indexes n are determined by the number of items in your original data structure $scope.json.

If you need to retrieve all values, you can iterate through your original object using the following function:

$scope.testing = function () {
    var answers = {sections: []};

    for (var i = 0; i < $scope.json.section.length; i++) {
        if (!answers.sections[i]) {
            answers.sections[i] = {answers: []};
        }

        for (var j = 0; j < $scope.json.section[i].questions.length; j++) {
            if (!answers.sections[i].answers) {
                answers.sections[i].answers = [];
            }

            answers.sections[i].answers[j] = $scope.json.section[i].questions[j].value
        }
    }
}

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 for adding a Search Bar to the header in a React Native application

I've been working on creating a header for my app in React Native that includes the screen title, a back button, and a search bar spanning the width of the screen. However, I've encountered some challenges along the way. Initially, I began with ...

React-easy-crop simply provides a blob url as a result

Currently, I am utilizing the react-easy-crop package to enable users to make adjustments to their profile pictures post uploading. However, I have encountered an issue where the cropped image is returned in the form of a blob URL such as blob:http://local ...

How to retrieve the clicked value using jQuery within a jinja2 loop

I'm currently working on an app that utilizes a Flask backend and Jinja2 templating. Within the HTML, I have a loop set up to organize data into batches, creating three columns on the web page: {% for batch in df.iterrows() | batch(3) %} <d ...

How to use Sencha Touch to automatically target a textfield on iOS programmatically?

My goal is to implement a pin login feature similar to the ones found on iOS and Android platforms, where users are required to enter a 4-digit pin to proceed. The issue I'm facing is that I want the input field to be automatically selected and the nu ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

Converting an array of objects into a single object: A step-by-step

I'm looking to transform an array of objects into a final output of objects. My initial array of objects looks like this: [ { "id": "11", "value" : "9999","sample":"1"}, { "id": "22", "value" : "8888","sample":"2"}, { "id": "33", "value" : ...

Utilize JQuery to identify and select every parent element, then retrieve the height of the first child element and adjust the height of the

Recently, I developed a PHP script that pulls news and case posts from a database. The HTML structure used for displaying these posts is as follows: <a href='/post/placeholder'> <div class='col nopadding col12-12 counter'> ...

Is there a glitch in my redux-saga?

After developing a React Native app, I encountered an issue with my index.ios.js file where I was adding middlewares to the store. import React, { Component } from 'react' import { AppRegistry, } from 'react-native' import { Provider ...

Creating a mask for both integer and decimal values in jQuery

I have created a validation mask in my code to verify user input when onBlur unitprmask:/^\d+,\d{1,1}$/, However, the current mask only allows for decimal numbers, requiring at least one decimal place. I want users to be able to enter whole in ...

Only retrieve one result from v-for loop depending on the key value

My v-for loop is set up to display a single result based on the chosen :key value from the counter data property. Everything is working well, but I am encountering problems when I try to add <transitions> for a smoother update of the value. The issue ...

Move the sprite to the center bottom of the orthographic camera

Looking for help positioning sprites at the bottom center of the orthographic camera. Here is the current setup - The object: function Obj() { const texture = useLoader(THREE.TextureLoader, loadedimg); const spriteRef = useRef(); return ( < ...

What is the simplest way to extract only the error message?

Having this code snippet. $('div#create_result').text(XMLHttpRequest.responseText); If we look at the content of XMLHttpRequest, it shows: responseText: Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"} st ...

Ways to terminate a looping function in jquery

My latest project involves creating a function that loops through a set of divs, fading in and out the next one. The challenge I'm facing is figuring out how to stop this loop upon either a click event, an if/else condition, or focus. After some resea ...

Create a dynamic and interactive website using a combination of jQuery and AngularJS

I recently came across an interesting tidbit on the FAQs of Angular stating that "Angular can use jQuery if it's present in your app when the application is being bootstrapped". This got me thinking, is it considered a best practice to include both j ...

`Is there a way to sort a deeply nested object by its values?`

I need assistance sorting an array of hospitals based on the lowest value of the amountinINR key, especially when dealing with deeply nested arrays of hospital objects. Does anyone know how to achieve this without using third-party libraries like lodash or ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

Utilizing the ref received from the Composition API within the Options API

My current approach involves utilizing a setup() method to bring in an external component that exclusively supports the Options API. Once I have imported this component, I need to set it up using the Options API data. The challenge I face is accessing the ...

Is there a way to automatically override the CSS cursor style?

Issue with SCSS styling on image link I attempted to modify the cursor style from pointer to default, but after saving and reloading my React app, the change did not take effect. I tried writing some code, but it seems that Stack Overflow is indicating an ...

My program contains redundant sections that are being repeated multiple times, and I am unsure of how to remedy this issue

This particular payment gateway relies on a paid market for processing transactions. Unfortunately, there seems to be an issue where multiple error messages are being triggered during the payment verification process. The errors include: ❌ | An error h ...