The AngularJS controller does not have its array initialized

Creating a small dialog controller where questions, answers, and correct answer index can be added. The goal is to allow users to add multiple questions and save them in an array.

Everything works smoothly until attempting to push the JSON data of the question details into a previously created array. When trying to push, JavaScript throws an error:

Cannot read property 'push' of undefined
. Researched how to push values into an array in Angular but couldn't find an exact solution for this issue.

Below is the code snippet:

function TestController($mdDialog, $scope, $mdSidenav, $mdBottomSheet, $timeout, $log) {
    $scope.questionSet = [];
    $scope.question = {
        text: null,
        answers: [],
        correctIndex: -1
    };

    $scope.clickPoP = function(ev) {
        // Dialog appended to document.body
        var parentEl = angular.element(document.body);

        $mdDialog.show({
            parent: parentEl,
            targetEvent: ev,
            templateUrl: "edit-word-dialog.tmpl.html",
            locals: {
                items: $scope.question
            },
            controller: DialogController
        });

        function DialogController($scope, $mdDialog) {
            $scope.cancel = function() {
                $mdDialog.hide();
            }

            $scope.addQuestion = function(nextQuestion) {
                if (nextQuestion === true) {
                    console.log($scope.question);
                    $scope.questionSet.push($scope.question);
                    console.log('added question - clearing object - waiting for next input');
                } else {
                    console.log($scope.questionSet);
                    console.log('added question- closing dialog box');
                    $mdDialog.hide();
                }
            }

            $scope.setAnswer = function(index) {
                $scope.question.correctIndex = index;
                console.log(index);
            }
        }
    };
}

The defined questionSet should store the questions. In the addQuestion() function, I attempt to push the JSON object with all necessary data into questionSet, resulting in the error.

Tried verifying data bindings, everything seems correct yet unable to push JSON into the array. Precaution was taken to avoid appending to simplify management. It's worth noting that my experience with Angular is limited.

Thank you for assistance! Apologies for the lengthy explanation.

Showcasing the dialog box code below, in case the error traces back here:

<md-dialog class="email-dialog" flex="80" flex-sm="100">
<md-toolbar class="toolbar-default" md-theme="{{triSkin.elements.toolbar}}" palette-background="myPurple:500">
    <div class="md-toolbar-tools">
        <h2>
          <span>Quiz</span>
        </h2>
        <span flex></span>
    </div>
</md-toolbar>
<md-divider></md-divider>
<md-dialog-content class="sticky-container">
    <div>
        <md-content>
            <md-input-container>
                <label for="question-text">Enter Question</label>
                <input type="text" id="quiz-question" label="quiz-question" name="quiz-question" ng-model="question.text">
            </md-input-container>
            <div style="float: right; width: 10%">
                <md-radio-group>
                    <md-radio-button value="0" aria-label="ans0" ng-click="setAnswer(0)"></md-radio-button>
                    <br/>
                    <br/>
                    <md-radio-button value="1" aria-label="ans1" ng-click="setAnswer(1)"></md-radio-button>
                    <br/>
                    <br/>
                    <md-radio-button value="2" aria-label="ans2" ng-click="setAnswer(2)"><//md-radio-button>
                    <br/>
                    <br/>
                    <md-radio-button value="3" aria-label="ans3" ng-click="setAnswer(3)"></md-radio-button>
                </md-radio-group>
            </div>
            <div style="float: right; width: 80%;">
                <md-input-container>
                    <label for="answer-one">Enter answer</label>
                    <input type="text" id="quiz-answer-one" label="quiz-answer-one" name="quiz-answer-one" ng-model="question.answers[0]">
                </md-input-container>
                <md-input-container>
                    <label for="answer-two">Enter answer</label>
                    <input type="text" id="quiz-answer-two" label="quiz-answer-two" name="quiz-answer-two" ng-model="question.answers[1]">
                </md-input-container>
                <md-input-container>
                    <label for="answer-three">Enter answer</label>
                    <input type="text" id="quiz-answer-three" label="quiz-answer-three" name="quiz-answer-three" ng-model="question.answers[2]">
                </md-input-container>
                <md-input-container>
                    <label for="answer-four">Enter answer</label>
                    <input type="text" id="quiz-answer-four" label="quiz-answer-four" name="quiz-answer-four" ng-model="question.answers[3]">
                </md-input-container>
            </div>
            <div style="float:left;">
                <md-button class="md-primary" aria-label="AddQuestion" ng-click="addQuestion(true)">Add Question</md-button>
                &nbsp;
                <md-button class="md-secondary" aria-label="Save" ng-click="addQuestion(false)">Save</md-button>
            </div>
        </md-content>
    </div>
</md-dialog-content>
<div class="md-actions" layout="row">
    <span flex></span>
    <md-button class="md-primary" aria-label="Close" ng-click="cancel()">
        Close
    </md-button>
</div>

Answer №1

In the context of your code, it is important to note that $scope.questionSet should be defined in the parent controller rather than in the dialogcontroller.

By default, MdDialog utilizes an isolated scope. To access the parent controller scope, you can pass scope: $scope in the $mdDialog call within TestController.

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

I'm having trouble getting the animation to work with jQuery. Despite trying everything, the animation doesn't seem to respond to any button clicks

Issue: I am facing a problem where nothing happens when I click the menu on the HTML page. It seems like a total beginner mistake, but I can't seem to get it to work. I have checked the code, and alert works fine, indicating that jQuery is connected t ...

Ways to authenticate custom kinds in JSON schema?

When working with JSON Schema, one of the challenges I have faced is the limitation on supporting ‘double’ and ‘float’ types for numeric values. While using AJV in JavaScript to validate a schema, it fails due to this restriction. Is there a way to ...

The benefits of using Node.js for asynchronous calls

Each time a new data is added or existing data is updated, the variables new_data and updated_data will increment accordingly. However, when attempting to output the total count of new_data and updated_data at the end of the code, it always shows as 0. H ...

Conceal a div once the content in a separate div has finished loading

After loading an image in slices inside a div, I want to ensure that the entire content is loaded before displaying the div. To achieve this, I am using another div as a mask while the content loads: <div id="prepage" style="position:absolute; left:0px ...

Combining Angular with Google Maps

Currently, I am utilizing angular-googlemaps(agm) and it has been functioning well for me so far. However, I have a requirement to search for an address using latitude and longitude. After some research, I discovered a partial solution here. The only issu ...

`Generating an ever-changing masonry layout on a website using live data`

I'm currently working on a new web project and I want to incorporate a masonry view for the images on the homepage. The plan is to host this project on Azure, using blob storage for all the images. My idea is to organize the images for the masonry vi ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

NodeJS controller function to generate and send a response

I'm facing an issue with my controller method where I am unable to send a response to the user, even though the value is displaying in the console. Below is my code snippet: const hubHome = (req,res) => { const hubId = req.params.hubId; fetch ...

Guide to smoothly transition the highlighted <tr> element to the top of the scroll bar

Is there a way to utilize jQuery for animating a selected row to the top of a div with a specific scrollbar style? #sc { border:1px solid black; width:450px; height:80px; overflow:scroll; } <div id="sc"> <table id=&quo ...

Adding a div after a specific child in a bootstrap grid

I've been searching tirelessly, but I just can't seem to crack this puzzle... In my Bootstrap grid, I'm faced with the challenge of injecting a div upon click after the row where the clicked div is located. For instance, I have a series of 5 ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

MariaDB won't generate JSON output for a column that has a JSON data type

Currently, I am utilizing MariaDB and phpMyAdmin to effectively manage my database. Within one of my tables, I have a specific field that is defined as type json, or alternatively longtext. However, whenever I execute a SELECT query using JSON_EXTRACT(fiel ...

`In the event that a series of criteria is unfulfilled in a JavaScript forEach() loop`

My IntersectionObserver utilizes a forEach method to invoke certain functions when a condition is met for each item in an array: const sections = document.querySelectorAll("section") function removeHighlight(id) { someElementArray[id].cl ...

Navigating Crossroadsjs Routing: A Beginner's Guide

After exploring various resources to understand how crossroads works, I stumbled upon a question on Stack Overflow that resonated with my struggles. However, despite spending hours trying to implement it, nothing seems to be working. The documentation on i ...

Anticipate the arrival of the getJSON response

Currently, I am working on a script that utilizes Yahoo's YQL within a web application. This script is designed to scan through a text paragraph, identify references, and display them as popups within the text. Everything works smoothly until I reach ...

Injecting dynamic content using JavaScript

My goal is to develop a web page where clicking on any of the three images will cause the content to be inserted into the empty div located above the image links. Below is the JavaScript code I'm using: <script type="text/javascript" src="js/jque ...

Ways to implement varying services based on route parameters

Imagine having two services with similar APIs but different implementations. myApp.module('myModuleApp').service('BananaService', function() { this.name = 'banana'; }); myApp.module('myModuleApp').service(&apo ...

Converting nested JSON strings to JSON structs in Play JSON

I need assistance with using the play json library's update method to convert a nested JSON string into a JSON struct. I am struggling with getting the syntax right. Can someone please provide me with guidance on this matter? The describes the usage ...

Transforming hierarchical objects into a relational database structure

I have JSON data containing user profiles that I plan to analyze using SPSS in the future. Currently, I imported the data into Google Refine for some data cleansing. However, my issue is that the original JSON includes nested objects, such as the "professi ...

Alert for every URL modification

Is it feasible to receive (event) notifications for every URL change (without refreshing the page, as possible with location.replaceState())? To clarify: I am not altering components or pages, just updating the URL for future reference. UPDATE Potential ...