Angular multiple checkbox array iteration in ng-repeat

I am currently working on a form using Angular and facing a challenge with a specific section.

Within the form, there is a 'Divisions' segment that includes a list of checkboxes generated dynamically from an API call. Users are required to select 1 to 7 checkboxes to identify the 'Division' the form is associated with.

Upon form submission, the JSON should display as Divisions: 'div1 div2 div3 div4'

The issue I am encountering is the inability to select multiple checkboxes simultaneously. Whenever I attempt to select another checkbox, the previously selected one gets unchecked.

Below is the code snippet I am currently utilizing.

        <label>Divisions Participating*</label>
        <div class="radio-check-wrap">
            <ul class="radio-check-group">
                <li ng-repeat="d in divisions">
                    <input type="checkbox" 
                           ng-model="tradeshow.DivisionLead" 
                           ng-true-value="div{{$index}}" 
                           class="" id="div{{$index}}" 
                           name="div{{$index}}" />
                    <label for="div{{$index}}">{{d.Description}}</label>
                </li>
            </ul>
        </div>

Additionally, in the controller, there is

$scope.divisions = Api.divisions.query();
and $scope.tradeshow = {}.

Can anyone provide insight as to why I am facing this limitation with checkbox selection?

Answer №1

Your checkboxes are set up to update the selected value within the same scope object. This means that as one checkbox is checked, the ng-model is updated to reflect the new selection while removing the check from any previously selected checkboxes.

If you'd like to explore different approaches to this issue, you can check out this answer: How do I bind to a list of checkbox values with AngularJS?

To demonstrate how to handle an object array as input data, you can view the changes I made in this example: http://plnkr.co/edit/otVgVMtwUGkIwr2uaSpq?p=preview

To ensure that the "selected" value is stored within each item and compute which are selected, I modified your checkboxes to the following:

<input type="checkbox" ng-model="d.selected" class="" id="div{{$index}}" name="selectedDivisions[]" />

I have also updated your code with methods for retrieving and storing the selected values:

$scope.divisions = [
  { Description: 'test1' },
  { Description: 'test2' },
  { Description: 'test3' },
  { Description: 'test4' }
];

// selected divisions
$scope.selection = [];

// helper method
$scope.selectedDivisions = function selectedDivisions() {
  return filterFilter($scope.divisions, { selected: true });
};

// watch divisions for changes
$scope.$watch('divisions|filter:{selected:true}', function (nv) {
  $scope.selection = nv.map(function (division) {
    return division.Description;
  });
}, true);

Answer №2

This solution appears to meet your needs - it involves an array of checkboxes, all connected to a single model:

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

Issues with router middleware functionality in Node.js hinder proper operations

Currently, I am working with Nodejs and utilizing "Express js". One of the tasks at hand involves implementing a "Router Middleware" function. With my current code setup, whenever I access "http://localhost:3000", the "router middle" functionality is tri ...

There is a delay in updating ng-if/ng-hide in real time on the HTML page

Assistance needed for implementing a slight adjustment in AngularJS with TypeScript. The requirement is to change the text of a button for 3 seconds upon clicking, then revert back to its original text. Two HTML elements are created for this purpose, each ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Alter the background shade of an item as it is added or removed from a multi-select list and transferred to another list

Is there a way to visually represent the movement of items between two multi-select lists? I have one list on the right and one on the left, and when objects move from right to left, I want them to have a red background (indicating removal) and if they mov ...

Exploring ways to track file upload progress with the Fetch API in ReactJS or NextJS

Currently, I am utilizing Nextjs for constructing a full-stack application. Specifically, I am focusing on the admin CMS part and attempting to implement file uploads such as images. Referring to this modified version of the code from this post. The upload ...

How can I implement $compile to execute a function on every row using angularjs and razor?

UPDATE: It seems that there is some confusion here, I am looking to apply the function to all rows, without using '', "", '"... After conducting some research, I have discovered that I will need to utilize $compile, but I am ...

What is stopping me from injecting an Angular controller?

After some consideration, I made the decision to alter the way in which I inject my controller. I successfully utilized the "$inject Annotation" method, following the instructions provided here. NetworkInterfaceDetailedViewController.$inject['$scope& ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

reasons why my custom attribute directive isn't functioning properly with data binding

Here is a snippet of the code I am working on, with some parts omitted for brevity: template.html ... <tr *ngFor="let item of getProducts(); let i = index" [pa-attr]="getProducts().length < 6 ? 'bg-success' : 'bg-warning'" ...

What is the best way to incorporate text transitions using jquery?

Recently, I've come across this code snippet: $('#slider_title').text(var); This line of code successfully adds the text stored in a variable to the paragraph identified by the id "slider_title". And now, my goal is to smoot ...

Error in Gulp caused by attempting to minify JavaScript files

I've been struggling with this issue for the past 2 days and I'm a bit of a novice when it comes to task runners. I decided to ask for help because I can't seem to figure it out on my own. Currently, I am using Gulp with Slush generated by ...

Each loop iteration results in the array being randomly ordered

My goal is to store multiple objects in an array and then render them out in a specific order. This is my process: app.js var allOdds = []; var count = 0; // ===================================== /* Database Configuration and Error Handling */ // ====== ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

Change the size of the font with a slider in VueJS

I have been utilizing the project found at This particular project allows end-users to reuse Vue components as editable sections by providing a styler overlay for adjusting content within a div or section. After installation, I added a slider which now ap ...

Discovering the distinction between arrays of JQuery objects

I have a task that requires the following steps: var elems = $('.lots-of-elements') Next, I need to make an AJAX request and then do this: var moreElems = $('.lots-of-elements') Finally, I am looking to identify only the new element ...

The setTimeout functionality is executing faster than expected

In my selenium test, I've noticed that the setTimeout function consistently finishes about 25% faster than it should. For example, when waiting for 20 seconds, the function completes after only 15 seconds. test.describe('basic login test',f ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

Guide on linking Influxdb information in a Vue application using node.js?

I have successfully connected my InfluxDB database to my Vue app and can log data in the terminal using the code below: // index.js import express from "express"; // These lines make "require" available import { createRequire ...

Determine the presence of a JSON Value/Array in a web application using JavaScript and visualize the information in a dynamic

Utilizing the Ticketmaster API has provided me with a sample dataset from their platform, Data 1 - Including information on "presales." "sales": { "public": { "startDateTime": "2019-11 ...

Trigger an event when the menu is outside the viewport and then lock the menu to the top of the viewport

I am trying to create a menu element that remains fixed at the top of the browser viewport as the user scrolls, ensuring it is always visible. In my webpage layout, the menu sits below some text in the header initially. Once the user scrolls past the heade ...