Nested ng-repeat in AngularJS allows you to loop through arrays

I am currently facing an issue with updating the choices in my object that contains a question and list of choices. I'm using nested ng-repeats to display this object on the page. While changing the 'question' works perfectly fine, modifying the 'choice' does not reflect any changes. Can someone help identify where the problem might be?

Here's how my page layout looks:

<div class="panel">

<div class="row">

    <div class="large-12 columns">

        <h3>{{ title }}</h3>

            <ol>
                <li ng-repeat="q in quiz">
                    <input type="text" ng-model="q.question">
                    <ul class="remove-li-dots">
                        <li ng-model="choice" ng-repeat="choice in q.choices">
                            <input type="text" ng-model="choice" name="answer{{ q.id }}" >
                        </li>
                    </ul>
                    </br>
                </li>
            </ol>
            <a class="button" ng-click="submitQuiz()">Submit</a><br>
            {{ quiz }}
    </div>

</div>

Take a look at a screenshot of the page here:

Answer №1

The issue at hand is that the choice variable is a string, so any changes made to it within a child scope will only affect that specific scope.

To resolve this, you should reference the choice by its index in the array using

ng-repeat="(choiceIndex, choice) in q.choices
,
ng-model="q.choices[choiceIndex]"
.

Additionally, to prevent inputs from losing focus when items are changed, be sure to include track by $index in the ng-repeat directive.

<ol>
    <li ng-repeat="q in quiz">
      <input type="text" ng-model="q.question">
      <ul class="remove-li-dots">
        <li ng-model="choice" ng-repeat="(choiceIndex, choice) in q.choices track by choiceIndex">
          <input type="text" ng-model="q.choices[choiceIndex]" name="answer{{ q.id }}">
        </li>
      </ul>
    </li>
  </ol>

Here is a working example: http://plnkr.co/edit/GJacjkzfT4FpfC6szsNk?p=preview


If you want a better grasp on how angular scopes function, I recommend checking out this link for more insights: https://github.com/angular/angular.js/wiki/Understanding-Scopes

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

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Looking for assistance with $.ajax - How can I send an object with key-value pairs?

I want to utilize $.ajax to send data in this manner: $.ajax({'url': 'my.php', 'type': 'POST', 'data': arr, 'success': function(response) { alert(res ...

Implementing AngularJS html5mode alongside nodeJS and Express

Currently, my AngularJS application is being served by a nodeJS server with Express. Everything runs smoothly when using the default angularJS routes (hashbangs); however, I am now attempting to enable html5 mode. To activate html5mode, I have implemented ...

Is it possible to make changes to a nested field in Mongoose based on the value of another nested field?

I'm struggling to access a specific field on my Mongoose schema in order to update it when creating an endpoint. The schema I'm dealing with follows the structure outlined below: { "pollId":15, "userId":13, "n ...

Utilizing the `useNavigate` function from react-router v6 within a class component to navigate and manage

I have a situation where I need to redirect a class component to another page. To achieve this, I came up with a function that decorates the export of the class component in order to navigate within the component's state. import { useNavigate } from & ...

Tips on how to retrieve a variable from an array in Vue JS

New to Javascript and Vue, I am exploring examples to grasp the fundamental concepts. <template> /*<p v-bind:class="['bold', 'italic', isValid ? 'valid' : 'invalid']">*/ <p v-bind:class= ...

Working with Spline Offset Functionality in Three.js

I am working on creating 3D text from font glyphs. While TextGeometry can be used for this purpose, I prefer to manually draw the text because I need to apply an offset on the font splines. Currently, I have the splines with their respective points and I ...

Having trouble with an unexpected value in your Angular2 Service? Don't forget to add

I encountered an error in my Angular2 app: Error: (SystemJS) Unexpected value 'ReleasesService' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Here is my AppModule code: import { NgModule } fr ...

angular get request not receiving proper response from hosted server file

Can anyone figure out why this code is not functioning properly? $http.get('http://localhost:8383/api/login.php').respond(function (method, url, data, headers) { return authorized ? [200, customers] : [401]; }); I have an alternative sol ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...

Transferring webpage code through JSON from PHP to JavaScript

I am using the jquery_form plugin to send an HTML form to PHP, which then sends back a JSON object. Here is what PHP sends back: $content = "<div>ABC</div>"; $json = json_encode(array("content" => $content)); // Here I also send $json to M ...

Challenges arise when attempting to accurately determine the pixel count of animated elements

I'm facing an issue with this code where it doesn't produce any result. The variable is needed since the number varies each time the user clicks. Is it not possible to define the number of pixels in this way? Your help is greatly appreciated. $( ...

Struggling to integrate JavaScript animation into an AngularJS Directive

function percentToPixel(perc) { return ($(".stepNavContainer").outerWidth() / 100) * parseFloat(perc); } var app = angular.module('app', ["ngAnimate"]); app.controller("appController", function($scope) { }); app.directive("init-modal", funct ...

What is the process for transferring multiple files using a read stream in Node.js?

Suppose I have a folder containing two files, index.html and style.css, and I would like to send both of them. How can I achieve this with Node.js? Router.get('/', function(req, res) { var indexStream = fs.createWriteStream('path to index ...

event handler in JavaScript that triggers upon a click

Encountering an issue with my code <tr> <td id="<?php echo; $id ?>" onclick="addrow(?php echo $id; ?>)">...</td> </tr> <tr id="<?php echo $id; ?>" class="ndisplay">...</tr> <tr id="<?php echo $i ...

Make sure to clear the POST data by returning an empty string following an Ajax request through Jquery and PHP

This is my HTML and JavaScript code: $.ajax({ url: 'post.php', type: "POST", data: 'name="dan"', success: function(result){ console.log(result); }, error: function(){ ...

Observing attribute changes in AngularJS directives

How can AngularJS observe attributes on a custom directive to bind Angular values? Here is my current progress: <tile title="Sleep Duration" data-value="{{sleepHistory.averageSleepTime}}"/> app.directive('tile', [function() { return ...

Discovering nested documents in MongoDB using JavaScript

How to find nested data in MongoDB with the following collection: { "_id": { "$oid": "585b998297f53460d5f760e6" }, "newspaper": { "playerID": "57bffe76b6a70d6e2a3855b7", "playerUsername": "dennis", "player_newspaper": "{\"ID\":\" ...

Issues with the functionality of the ZeroClipboard Angular plugin

"> I'm fairly new to Angular and currently experimenting with a module called ZeroClipboard. I've made adjustments to my application in order to incorporate the module and configured it as per the demonstration. var app = angular.module ...