Creating a complex array structure using checkbox inputs within an Angular application

In my Angular application, I have a list of checkboxes that are dynamically generated using nested ng-repeat:

<div ng-repeat="type in boundaryPartners">
    <div class="row" ng-show="showBPtype[$index]">
        <div class="col-xs-12">
            <div ng-repeat="partner in type.partners">
                <label class="checkbox-inline">
                    <input type="checkbox"
                        value="partner.id"
                        ng-model="partner.selected"
                        ng-change="changeValue(partner)"
                    />
                    <p><span ></span>{{partner.name}}<p>
                </label>
            </div>
        </div>
    </div>
</div>

The data structure for this list is as follows (sample included):

{
    "id": 1,
    "name": "Civil Society Organizations",
    "partners": [{
        "id": 1,
        "name": "Youth Association"
    }, {
        "id": 2,
        "name": "Rwanda Network"
    }, {
        "id": 3,
        "name": "Communité du Rwanda"
    }]
},

{
    "id": 2,
    "name": "Educational Organizations",
    "partners": [{
        "id": 16,
        "name": "SchoolA"
    }, {
        "id": 17,
        "name": "SchoolB"
    }]
}

This array consists of partner types, each containing a list of partners within the "partners" array.

The functionality allows users to select partners through checkboxes and add them to a nested list of selected partners. A similar process removes partners when they are deselected.

A working solution has been provided by user Artyom Pranovich here.

To populate the nested list with selected partners based on the described interface, modifications need to be made to adapt the existing code.

The final list structure where selected partners will be added resembles the following:

[
    {
        "id": 1,
        "entities": [
            {
                "id": 2,
                "name": "Entity 2"
            },
            {
                "id": 3,
                "name": "Entity 3"
            }
        ]
    },
    {
        "id": 2,
        "entities": [
            {
                "id": 2,
                "name": "Entity 2"
            }
        ]
    }
]

Within the application, this list is referred to as

$scope.report.participatingPartners
.

Answer â„–1

If I have correctly grasped your issue, the solution should be quite similar to this one.

Should you have any inquiries, feel free to ask.

<div ng-repeat="organization in boundaryPartners">
    <div ng-repeat="partner in organization.partners">
        <label>
            <input type="checkbox" value="partner.id" ng-model="partner.selected" 
                   ng-change="changeValue(partner, organization, $parent.$index)"/>
            {{partner.name}}
        </label>
    </div>
    <hr/>
</div>

$scope.participatingPartners = []
var idsArray = [];

$scope.changeValue = function(partner, organization, index){
   if(partner.selected)
      addPartner(partner, organization, index);
   else
      removePartner(partner, organization, index);
};

var addPartner= function(partner, organization, index){
    prepareArrayToAdd(organization, index);
    if(!existInList(index, partner)){
        $scope.participatingPartners[index].partners.push(partner);
    }
};

var prepareArrayToAdd = function(organization, index){
    if(!$scope.participatingPartners[index])
        $scope.participatingPartners[index] = { id: organization.id, name: organization.name, partners: [] };
};

var removePartner= function(partner, organization, index){
    idsArray = getIdsArray(index);
    var indexToRemove = idsArray.indexOf(partner.id);
    if(indexToRemove == -1)
       return;

    $scope.participatingPartners[index].partners.splice(indexToRemove, 1);
};

var existInList = function(index, partner){
    idsArray = getIdsArray(index);
    return idsArray.indexOf(partner.id) != -1;
};

var getIdsArray = function(index){
    return $scope.participatingPartners[index].partners.map(function(partner){ return partner.id });
};

JSFIddle link.

I hope this information proves helpful!

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

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

I'm encountering an issue with my React master component not being able to locate the

I am having trouble importing a component in my APP.js file. I have been attempting to bring MainComponent into the app.js component, but I am facing difficulties in fetching the component. Any assistance in resolving this issue would be greatly apprecia ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

What is the best way to identify onKeyUp events in AngularJS?

Is there a way to detect when a user releases a key in AngularJS? I have been searching for an 'ngOnkeyup' directive, similar to ngChange, without any luck. If this specific directive doesn't exist, is there a simple method to trigger a co ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

Is it possible to bundle *.html templates using Require.js Optimizer functionality?

What is the best approach for packaging HTML templates (also known as 'partials') in an Angular.js app when it's concatenated and minified for distribution? Should they be included in the single file, or zipped along with other directories s ...

Troubleshooting Media Queries Problems in HTML and CSS

Check out the code snippet below: //Modifying text content (function() { var texts = $(".altered"); var textIndex = -1; function displayNextText() { ++textIndex; var t = texts.eq(textIndex) .fadeIn(2000) if (textIndex < te ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Learn the steps for converting data from xlsx or csv files into JSON format

I am currently working on developing an application that allows users to upload xlsx or csv files from the frontend and submit them to a backend built with nodejs and express for processing. However, when I receive the data in the backend, it appears in th ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

Utilize Bootstrap 3 Datepicker version 4 to easily set the date using Moment.js or Date objects

I'm currently utilizing the Within my project, I have a datetime picker labeled as dtpFrom <div class='input-group date ' id='dtpFrom'> <input type='text' class="form-control" /> <span c ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

Ways to show a corresponding number beneath every image that is generated dynamically

I have a requirement to show a specific image multiple times based on user input. I have achieved this functionality successfully. However, I now need to display a number below each image. For example, if the user enters '4', there should be 4 im ...

Infinite scroll layout meets Semantic UI visibility for a dynamic user experience

I am attempting to implement an infinite scrolling Masonry layout within the Semantic UI framework, utilizing the pre-existing visibility function. While everything appears to be functioning correctly, I am encountering difficulties with getting Masonry t ...

Prefering `window.jQuery` over the yarn version

I am currently in the process of transitioning to Vite 3 with Vite Ruby on Rails from Webpacker and Webpack. One major issue I have encountered is that my system functions as a CMS. Some of our long-standing clients have jQuery code embedded directly withi ...

Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this: tires: [{ name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct2", quanti ...

Apparent malfunctions in Bower packages

Here are some of the packages available on bower: bootstrap-ui, angular-ui-bootstrap, and angular-ui-bootstrap-bower. It appears that only angular-ui-bootstrap-bower has built js files. Can anyone provide more information on this? ...

What could be causing me to see a basic checkbox instead of a toggle switch in my React application?

I've been attempting to create a toggle switch that activates dark mode using Bootstrap switches, but when I save the code, it reverts back to a basic checkbox. According to the documentation, for older assistive technologies, these switch elements wi ...

Resolving DataTables Error

Here is my JavaScript code snippet. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.1/css/but ...