Obtaining a complex object from a Checkbox set in AngularJS through the use of ngModel

Hey there!

I've been searching on Stack Overflow regarding this topic, but I haven't found a solution that matches exactly what I need.

If you want to take a look at the code, here is a JSFiddle link for reference: http://jsfiddle.net/gsLXf/1/

Currently, I'm working on a survey with a dynamic set of questions. I have managed to bind text and radio responses to a 'response' object successfully. However, I'm facing an issue with checkboxes. In the fiddle example, when I use

ng-model="response[question.id]"

all checkboxes act as one entity since they are bound to the same value. On the other hand, if I try using

ng-model="response[question.id][option.id]"

I encounter an error because question.id hasn't been initialized yet, therefore option.id can't be added to the object.

The response object in the JSFiddle should ideally look like this:

{
   "123456": "2", //radio question
   "789012": //checkbox question 
       ["5", "6"] //list of selected checkbox option ids
}

Since my users will be creating forms dynamically, it's crucial for me to handle this gracefully under all circumstances. I cannot manually input any object-related data into a controller or create model objects specifically for this scenario.

I have thought about looping through the known ID set to structure a response object to be filled during initialization, but it feels like too much work considering Angular offers a simple way of creating response objects (except in this case).

What would be the most effective approach to deal with this situation?

Answer №1

If you're looking for a solution, check out this demo: http://jsfiddle.net/2jVtH/

An alternative approach is to use a custom directive called cbb, which simplifies the HTML structure like so:

<div cbb question="question" response="response"></div>

This not only streamlines the code but also enhances readability, especially if applied to radio buttons as well.

The directive creates an isolated scope and assigns checkbox values to an object within it:

scope.model = {}

By utilizing a deep $watch on this object, an array of values is updated to achieve the desired format, such as

response = { "789012": ["7", "8"] }
.

Here's the complete code snippet for the directive:

surveyApp.directive("cbb", function() {
    return {
        restrict: "A",
        scope: {
            question: "=",
            response: "="
        },
        template:
            "<div class='text'>{{question.question}}</div>" +
            '<div class="options" ng-repeat="option in question.options">' +
                '<input type="checkbox" ng-model="model[option.id]" value="{{option.id}}"/> {{option.value}}' +
                '<tags ng-if="option.tags"></tags>' +
                '<action ng-if="option.action"></action>' +
            '</div>',
        link: function(scope, element, attrs) {
            if( !scope.response[scope.question.id] ) {
                scope.response[scope.question.id] = [];
            }
            var result = scope.response[scope.question.id];
            scope.model = {};
            scope.$watch("model", function(newval) {
                var x;
                result.splice(0);
                for( x in newval ) {
                    if( !newval.hasOwnProperty(x) ) continue;
                    if( newval[x] ) result.push(x);
                }
            }, true);
        }
    };
});

Answer №2

Despite my best efforts, the Angular directive and HTML code I worked on still contain redundant empty strings in an array when a checkbox is unchecked.

To address this issue, I attempted to use ng-init:

ng-init="response[question.id] = []"

Here is the link to the jsfiddle:

http://jsfiddle.net/P9dsR/

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

When attempting to update a task with the Microsoft Graph API, the server returned a 400 error code

Attempting to update a Task using the Graph API from an angular2 typescript app. Here is an example of my request - Request URL:https://graph.microsoft.com/beta/tasks/_1EKXXuN1UGInJ9yVHAjIpYAKuC2 Request Method:PATCH Request Body: { "createdBy":"f16 ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

Vue transition not functioning properly when hovering over text for changes

When you hover over the circular region on the website, the text and description in the red box will change. To add a fade animation effect when the text changes, I attempted to use <transition> as per the documentation provided in this link. Unfor ...

What steps should I take to create an object that can be converted into a JSON schema like the one shown here?

I'm facing a rather simple issue, but I believe there's something crucial that I'm overlooking. My objective is to iterate through and add elements to an object in order to generate a JSON structure similar to the following: { "user1": ...

Updating a data with a JavaScript browser script

Recently, I have been attempting to modify the timer in a game using scripts found on various websites. My coding skills are not top-notch, so I am seeking some assistance. I am keeping my fingers crossed that the timer is not server-sided. Upon inspecting ...

jwplayer - track viewing time - monetize by the minute - trigger action based on duration

My goal is to track the time duration that someone watches a video, ideally by triggering an action every minute. I'm aiming to create a pay-per-minute system where a credit is withdrawn from the user for each minute they watch. If this setup isn&apo ...

Tracking changes to payment methods when an order is modified through the WooCommerce backend

In the midst of working on a project involving WooCommerce, I am currently focused on integrating a new feature. This feature involves adding an order note whenever a user modifies the payment method during the order editing process within the WooCommerce ...

The status value in the result has a whitespace just before the term "success"

Apologies for the unclear question, but I encountered a strange bug in my code. I am trying to show an alert to users informing them that the updates have been successfully completed. Below is the code snippet containing an if() block where the alert shoul ...

Unique Input Values in Forms

I'm encountering an issue with a basic HTML form connected to a PHP script for processing values. Despite thorough testing, the form is not functioning correctly. Upon inspecting the form markup, I discovered: <form id="delete_item_3_form" action ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Why can my JavaScript server code read "2011" but not "20,11" when both are formatted as strings?

Currently, I am trying to establish a connection between Storm and JavaScript through redis. While the redis aspect of the connection is functioning correctly, I am encountering an issue when attempting to publish tuples (essentially Strings). Even though ...

Leveraging React SSR with Next.js, we can utilize the `getInitialProps` method to insert a

When working on Next.js with server-side rendering in React, I encountered an issue while trying to render a page as shown below: // This common element is used in many projects through my private node_modules const Header = ({ result }) => <div> ...

Reducing the number of DOM manipulations for websites that heavily utilize jquery.append

Here's a snippet of my coding style for the website: !function(){ window.ResultsGrid = Class.extend(function(){ this.constructor = function($container, options){ this.items = []; this.$container = $($container); ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

How to calculate large integer powers efficiently in JavaScript using the mod

I'm currently on the lookout for a reliable JavaScript algorithm as I attempted to implement one using node.js : function modpow_3(a,n, module){ var u = BigInt('1'); var e = equals(a, u); if( e) return a; if(equalsZero(a)) return a; if(pair ...

Troubleshooting issue with Next.JS Redux dispatch functionality inside getStaticProps() not functioning as

I have recently started working with Next.JS and decided to integrate Redux into my Next.JS application. I'm facing an issue where my page is supposed to display a list of posts fetched from an API. Everything works fine when I use useEffect() to disp ...

Loading SVG images in advance

I am in possession of around one hundred simple SVG images, distributed among five different image folders. These images are currently retrieved on demand when they need to be displayed, which generally works well but occasionally results in flickering tha ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

The component data fails to reflect the updated value following a status change due to not properly retrieving the new result from the POST function

Below is the Vue.js 2 code snippet for sending data to the backend. The vuex library was used to manage the data status. After using the POST function, the result returned from the backend updates the value of sampleId. This value is auto-generated by the ...

Discover the hexadecimal color code generated from an rgba color

Do you know of a service that can determine the final hexadecimal value of an rgba color? For instance, if my body background-color is set to #FF0000 and my header is positioned over it with a background-color of rgba(0,0,0,.7), how can I find out what the ...