Ways to add elements to an array nested within services and append to an object within another object

 <pre lang="HTML">
 <ul>
 <li data-ng-repeat="q in QuizObj">
 <fieldset><legend>All Quizes </legend>
     <h1>{{q.Quiz  }}</h1>
     <h3>options</h3>
     <h3>answer</h3>
        &lt;input type="radio" />{{q.options[1]}}
        &lt;input type="radio" />{{q.options[2]}}
        &lt;input type="radio" />{{q.options[3]}}
        &lt;input type="radio" />{{q.options[4]}}
        <h4>Answer</h4>
        &lt;input type="radio" />{{q.answer}}
  </fieldset>
        </li>
    </ul>
 &lt;input type="text" ng-model="ans">
    &lt;input type="text" ng-model="Question" >

    &lt;input type="text" ng-model="type">
    &lt;input type="button" data-ng-click="addQuiz()">

and this is js angular code

angular.module('quizApp',[])
.controller('mainCtrl',function($scope,crudService){

$scope.name="this";
        alert(JSON.stringify(crudService.quiz));
        $scope.QuizObj= crudService.quiz;
    })
    .service('crudService',function(){
        this.quiz=[
            {
                Quiz: "what is the C#",
                options: {  1: 'P-lang',
                            2:'h-lang',
                            3: 'A-lang',
                            4: 'nothing'
                        },
                type: 'radio',
                answer: 1
            },
            {
                Quiz: "what is the J#",
                options: {  1: 'P-lang',
                    2:'h-lang',
                    3: 'A-lang',
                    4: 'nothing'
                },
                type: 'radio',
                answer: 1
            },
            {
                Quiz: "what is the VB",
                options: {  1: 'PL',
                    2:'hL',
                    3: 'AL',
                    4: 'nothing'
                },
                type: 'radio',
                answer: 1
            }
        ]

    })

i am encountering an issue while attempting to dynamically add questions to the quiz object that resides within a service. How can I achieve this? i have written the following function for adding new questions:

   $scope.addQuiz= function($scope){
                crudService.quiz.push({
                    Quiz: $scope.Question,
                    type: $scope.type,
                    answer: $scope.ans
                })

        }

However, I am facing the error message: TypeError: Cannot read property 'Question' of undefined How can I successfully push new data into the service's object (quiz)? Furthermore, how do I add options to each question in the quiz object? Additionally, I would like to give users the ability to specify the type of answer, such as true/false (checkbox), multiple answers (checkbox), or single answer (radio buttons). How can I implement this and structure the layout accordingly?

Answer №1

It seems like you forgot to include the $scope parameter in your call to the addQuiz() function. Since $scope is already within the scope of the addQuiz function, you don't need to pass it explicitly:

$scope.addQuiz = function () {
    crudService.quiz.push({
        Quiz: $scope.Question,
        type: $scope.type,
        answer: $scope.ans
    });
};

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

Modifying SVG HTML5 pattern attributes for a particular instance or use case

Having a SVG Pattern that serves as the fill for multiple other SVGs presents a challenge. Any changes made to the pattern attributes will reflect in all SVGs using it. Is there a way to customize the pattern attributes for a specific instance/use only? ...

A guide to serving multiple HTML files with Node.js

After creating a mongoDB form using nodeJS, I successfully served the signUp page. However, clicking on any other links to navigate to different pages resulted in an error message saying "Cannot GET /index.html". I am struggling with how to properly serv ...

Using Node.js to Perform Testing with VCR

Does anyone know of a testing system similar to VCR for node.js? Check out this link for more information. ...

Using Laravel and vue.js to convert values into an array

I am currently utilizing vue.js within my Laravel project. Within the project, I have three tables: Article Location article_location (pivot table) I am looking to convert location articles into JSON format so that I can pass it to vue. How should I ...

The functionality of Jquery .slideToggle("slow") seems to be glitchy when used as a table expander

I attempted to implement the .slideToggle("slow"); feature to my table, following the instructions detailed here: W3Schools The toggle effect seems to be functioning, but not as expected. I want the effect to behave similar to the example on the W3School ...

Anchor checkboxes

I am dealing with a large number of checkboxes that are linked to anchors. Whenever a checkbox is clicked, it navigates to the corresponding anchor on the same page. Is there a more efficient way to implement this? With around 50 checkboxes, my current cod ...

What is the best way to pass a VueJS object to be stored in a Laravel controller?

I am facing an issue with my methods where the data is not getting stored in the database. I am unsure why the information is not being sent to the controller. Even though I input the correct data, it fails to load into the database. However, it does pass ...

Error message: The login buttons from Meteor's accounts-ui-bootstrap-3 are not showing up on the webpage

Following the installation of bootstrap-3 and accounts-ui-bootstrap-3, the expected ui-accounts login widget was not displayed when using {{ loginButtons }}. Instead, a <div> appeared in place of the widget, with no actual widget visible. Are there ...

Real-time Email Validation: Instant feedback on email validity, shown at random intervals and does not persist

I am attempting to show the email entered in the email input field in a validation message. The input field also checks my database for registered emails and displays a message based on the outcome. I then included this code from a source. What happens is ...

I am having trouble with Django Bootstrap when trying to center this container

I've been struggling to center this div container following my navbar in order to achieve equal spacing on both sides of the page. Unfortunately, my attempts have been unsuccessful. Could anyone provide assistance, please? The issue seems to be occurr ...

Using SimplyJS and XML: extracting the value of a specific key

Hey there, I wanted to update you on my progress with the Pebble Watch project. I've switched over to using an official external API to make HTTP requests for values, and now I'm receiving results in XML format instead of JSON. Here's a ...

javascript please input the number of seconds, ensuring it is a non-negative value

I'm encountering a JavaScript issue where I need users to enter a number of seconds in an input field. The catch is that the number of seconds entered can't be less than zero. How should I approach this logic in the code? function sec(){ // ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Tips for concealing Bootstrap 5 modal exclusively after successful completion

Utilizing the power of Bootstrap 5 I have successfully implemented a modal that shows up when #truck_modal is clicked, thanks to the following JavaScript code: (this snippet is located at the beginning of my js file) document.addEventListener('DOMCo ...

Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript? function getJSONData() { var points = '{\"points\": ['; var params = polyline.getLatLngs(); ...

I am experiencing difficulties with the ng-disabled directive in AngularJS as it is not functioning

I'm attempting to toggle the button's enable and disable states based on a certain condition. So far, I have been successful in disabling the button using $scope.isDisabled = true;, but I am facing difficulty in enabling it again. Below is the ...

Slow and choppy animations with jQuery

I've been struggling with a slow and choppy jQuery animation despite trying various techniques to improve its speed. I've attempted stopping existing animations before starting new ones, ensuring animations are only performed when necessary, and ...

Discord bot that combines the power of discord.js and node.js to enhance your music

I am currently working on a Discord bot designed to play music in voice chat rooms. However, I am facing some issues with properties. Whenever I try to launch the bot using "node main", I encounter the following error message: "TypeError: Cannot read prope ...

Using Firebase callable functions with React Native

Can I use Firebase callable functions with React Native? I have successfully deployed an onCall function and it is visible in my dashboard. I have initialized the functions using: // Initialize Cloud Functions through Firebase firebase.functions(); The ...

Bootstrap Thumbnail Grid - dynamic loading with ajax

Situation: I am facing a challenge where I have a view displaying countries in a twitter bootstrap thumbnail grid. Upon clicking an image, the intention is to dynamically show cities related to that particular country within the same grid on the screen. T ...