Struggling to update the position of an array and dynamically show its contents using Angular

I am working with an Array of Objects, each containing an Array of strings. Utilizing ng-repeat to display all the strings, I have a button to switch to the next set of strings by changing the selected object in the outermost array. Below is the code snippet I am working with:

HTML

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="quizRadioButton.css"/>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="quizAngularJs.js"></script>
<title>American History Quiz</title>
</head>
<body ng-app="myApp">
    <div ng-controller="questionCtrl">
        <form>
            <h1>{{question}}</h1>
                <ul>
                    <li ng-repeat="choice in choices"><input type="radio" name = "answer">{{choice}}</li>
                    <li>{{count}}</li>
                </ul>
            <button ng-click= "upCount()">Submit Form</button>
            <button id='goBack'>Go Back</button>
        </form>
    </div>
</body>

Javascript

var myApp = angular.module('myApp', []);

function questionCtrl($scope){
var allQuestions = [....];
$scope.count = 0;
$scope.question = allQuestions[$scope.count].question;
$scope.choices = allQuestions[$scope.count].choices;

$scope.upCount = function(){
    $scope.count = $scope.count + 1;
};
}    

Each object in the array looks like this:

{
 question: "question A",
 choices: ["choice 1", "choice 2", "choice 3"],
 correct answer: 0
}

I have verified that the count is updating correctly. However, even though the count is updating, the view is not refreshing. I have attempted to adjust my function as follows, but it did not resolve the issue:

$scope.upCount = function(){
    $scope.count = $scope.count + 1;
    $scope.question = allQuestions[$scope.count].question;
    $scope.choices = allQuestions[$scope.count].choices;
};

Appreciate any assistance with this. Thank you.

Answer №1

You can keep allQuestions within the scope itself. It seems unnecessary to have two separate modules just to keep track of the current question. Using count alone should suffice.

var myApp = angular.module('myApp', []);
function questionCtrl($scope){
    $scope.allQuestions = [....];
    $scope.count = 0;
    $scope.upCount = function(){
        /* Ensure the index does not go out of range */
        if($scope.allQuestions[$scope.count + 1])
            $scope.count = $scope.count + 1;
    };
    $scope.upCount = function(){
        /* Ensure the index does not go out of range */
        if($scope.allQuestions[$scope.count - 1])
            $scope.count = $scope.count - 1;
    };
}    

Then, in your HTML, you can simply do:

<body ng-app="myApp">
    <div ng-controller="questionCtrl">
        <form>
            <h1>{{allQuestions[count].question}}</h1>
            <ul>
                <li ng-repeat="choice in allQuestions[count].choices">
                    <input type="radio" name = "answer">{{choice}}</li>
                <li>{{count}}</li>
            </ul>
            <button ng-click= "upCount()">Submit Form</button>
            <button id='goBack'>Go Back</button>
        </form>
    </div>
</body>

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

What is the best way in Javascript to retrieve and process multiple stream chunks from a single API request using the fetch() method

I'm dealing with a Node/Express backend where there is a lengthy (10 - 15sec) API call that is responsible for setting up a user's account. To initiate this action from the front-end, I simply use a fetch('my/api/url') GET request. My ...

Assigning a class to an li element once the page has finished loading

I am facing an issue with my navigation bar where the links are dynamically loaded from a database using a foreach loop. Although the nav bar is static, I want to apply an 'Active' class to the link when it is currently active. Despite trying to ...

Exploring Grails Assets, Redirections, Secure Sockets Layer, and Chrome

Using Grails 2.1.1 with the resources plugin, I have encountered an issue when incorporating the jstree library which comes with themes configuration: "themes":{ "theme":"default", "dots":false, "icons":true } The JavaScript in the library locat ...

Guide on submitting a form using a custom AJAX function based on the id or class parameter

Instead of writing an ajax call every time with changing API URL, post method, and form id or class name based on the page, I am attempting to develop a custom function that can manage the API call based on the provided parameters. The essential parameters ...

Experiencing difficulties integrating relational data with Angular and MongoDB

I have a view where I display 'Transporters'. Each Transporter has multiple 'Deliveries', so I want to associate Deliveries with the corresponding Transporters. My tech stack includes express, mongoose, and angular.js. Here are my mode ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

What is the designated action or code in question?

let specialty = ''; function isVegetarian() { }; function isLowSodium() { }; export { specialty, isVegetarian }; export { specialty, isVegetarian }; The explanation from the editor was as follows: When exporting objects, it is done by the ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

What is the best way to remove a selected item from an array in Vuejs when it has been clicked

I'm having trouble with my splice() method in this simple To-Do app. I want to delete a specific task by clicking a button, but the solutions I've tried from Stack Overflow aren't working for me. The items do get deleted, but only the last o ...

prismjs plugin for highlighting code displays code in a horizontal format

If you're looking for a way to showcase source code on your website with highlighted syntax, prismjs.com may be just what you need. It offers a similar style to monokai... However, I've encountered an issue where the plugin displays my code in a ...

When using Intl.DateTimeFormat, unexpected output may occur when formatting dates prior to the year 1847

Why do dates before 1848 result in May 10 when formatted? Could this be related to time zones? And if so, how can I prevent this issue when creating a date object from an ISO date string like YYYY-MM-DD format? (Tested on Chrome 59) const workingDate ...

When the user signs in with Next-auth, they will be redirected to /signin with

After following the documentation to implement next-auth, I encountered an issue. When I visit http://localhost:3001/api/auth/signin, I see a page with a link (https://i.stack.imgur.com/xb0fx.png) but clicking "signin with Google or GitHub" just refreshes ...

Type in the password for Bluetooth devices in an Ionic application

I have successfully established a connection between my Ionic/Angular app and some BluetoothLE devices. According to the documentation at https://github.com/randdusing/cordova-plugin-bluetoothle, only the address is required for the connection (no passwor ...

Various colored backgrounds in a random arrangement on a grid post layout

I'm looking to implement this plugin for displaying blog posts, but instead of using an image as the background, my client wants different colored images. I have managed to figure out the code to achieve this based on a post I found here, but unfortun ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

Differences between Jquery's Find Method and ID Attribute

In my search for efficiency, I am currently exploring ways to quickly access an element. Which method is faster: $('body').find('#elemID'); vs. var id = $('#elemID'); ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

Unable to trigger onSelect event on the datepicker component

Whenever a date is chosen, I need to trigger a javascript function. Here is the javascript code: $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap- ...