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

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...

Utilizing HTML to emphasize a section of text

Hey there! I have a question related to an image with unicodes. The letter featured in the image was written using unicode characters పా. I'm trying to highlight the white portion of the image, but simply replacing it with ా isn&apos ...

Limit the outcomes of the Ionic timepicker

Currently, I am utilizing the ionic datetime feature. However, instead of receiving just the hours, minutes, and seconds, the result I am getting looks like this 2020-10-05T00:00:27.634+07:00. What I actually require from this output is only 00:00:27. Is ...

How to effectively utilize string and table data types in Oracle stored procedures

I'm facing a challenge in an Oracle stored procedure where I am working with a type table containing 2 columns and need to extract one column for use in the procedure's WHERE clause. For example, I have a type array called EData with columns ID ...

If the variable is empty, use jQuery ajax to send a request with different data

Below is the code I have written: $(document).ready(function() { cookieanimalid =($.cookie("cookieanimal")); $.ajax({ type: 'POST', url: "/myurl/", data: {cookieanimalid}, success: function ( ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

Converting JavaScript code to React requires excluding jQuery

I have been working on updating my old JavaScript code to make it compatible with React. The main goal is to integrate external data into a 3rd party form. Here is the original JS code: <script charset="utf-8" type="text/javascript" ...

Increasing the margin-left automatically in Bootstrap 3.0.0

I am looking to automatically generate margin-left in the ".card" class "style" element every time a post is entered on a page. My jQuery version is 1.12.4 This is my idea: If the .card CSS style has a margin-left of 0 and width of 479px, set position to ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...

Is it advantageous to combine socket.io with express for seamless communication in web applications? If the answer is yes, what is the best approach to integrating

Embarking on my journey into back-end development, I am currently delving into the task of creating a simulated money poker website. Leveraging Node.js along with socket.io, express-session, and passport, I initially relied heavily on express with an HTTP ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Calculating the Median of Vectors in Google Sheets

I need to find the median of rows in a matrix so that I get a vector with each element representing the median of its respective row. For instance, if we have the matrix {1,2,3;4,5,6}, the result would be MedianRowWise{1,2,3;4,5,6} = {2;5} As opposed to ...

Utilizing BackboneJs to Access and Fetch Data from an asmx Webservice

Could someone please help me with a code snippet to understand how to call asmx web services from a backbone collection? The provided example is very simple. Collection window["Persons"] = Backbone.Collection.extend({ model: Person, url: ...

Using Javascript with Selenium to choose an item from a dropdown menu

I'm having trouble selecting an element from a dropdown list and interacting with it. The xpath for the element I'm trying to select from the dropdown is: /html/body/div[1]/div/div[1]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div/div/div/div[2] ...

Using AJAX to send both data input values and file attachments simultaneously to a PHP server

I am currently having an issue with sending form values to my PHP page using AJAX. My form includes text inputs and a file input for image uploads. Below are the AJAX codes I have been working on: function sendval() { var form = $('#user_update_for ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

What situations call for utilizing $scope directly?

As a beginner in Angular, I have been diving into various tutorials to enhance my knowledge. Interestingly, the free tutorial at CodeSchool, which served as my introduction to Angular, does not mention the use of $scope. It appears that the controllerAs s ...