Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration.

<li ng-repeat="player in team.players">
  <div class="row">
     <div class="col-md-3 m-t-xs">
       <input type="checkbox" ng-model="vm.newEvent.players[$index].selected" ng-change="vm.selectPlayer($index, player)"> {{player.name}}
     </div>
     <div class="col-md-5 m-t-xs">
        <label for="">
         <input type="radio" name="{{player.id}}" ng-change="vm.disSelectPlayer($index, player)" ng-model="vm.newEvent.players[$index].casuality.type" value="injured"> Injured
        </label>
        <label for="">
         <input type="radio" name="{{player.id}}" ng-change="vm.disSelectPlayer($index, player)" ng-model="vm.newEvent.players[$index].casuality.type" value="sick"> Sick
        </label>
        <label for="">
         <input type="radio" name="{{player.id}}" ng-change="vm.disSelectPlayer($index, player)" ng-model="vm.newEvent.players[$index].casuality.type" value="other"> Other
        </label>
     </div>
  </div>
</li>

This is how it appears in the browser at the moment.

https://i.sstatic.net/gnPHZ.png

The problem arises when I click on any player name in the FC Barcelona Accordion, as it also selects the player with the same index from the FC Bayern Munich Accordion. What I aim for is to maintain the separation of all players individually. Is there something missing in the binding process?

Answer №1

Discover how checklist-model, an AngularJS directive, simplifies managing lists of checkboxes

While in Angular, each checkbox

<input type="checkbox" ng-model="...">
typically corresponds to a single model, it is common practice to store multiple checked values in an array using one model. Checklist-model eliminates the need for extra controller code by addressing this requirement. To implement this, simply adjust the attributes of the <input type="checkbox"> tag:

  • replace ng-model with checklist-model
  • specify a value for checklist-value to determine the array item

Explore the Documentation

Answer №2

This issue arises due to the function:

vm.disSelectPlayer($index, player)

To differentiate each player, you should include an index in the following code:

<li ng-repeat="player in team.players">

Here is a solution:

<li ng-repeat="(key ,player) in team.players">

Then, make sure to use this key in the function call as well:

vm.disSelectPlayer($index, player, key)

I hope this helps solve your problem :)

Answer №3

The reason for this error is that in line #4, you have written

ng-model="vm.newEvent.players[$index].selected".

Instead of using the parent object players, you can simplify it by using

ng-model="vm.player.selected".

OR

ng-model="vm.team.players[$index].selected".

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

How can jQuery verify if an input value is contained within an array?

I've been attempting to verify if the value of an input field is part of an array, but for some reason it's not working. Here is my approach: var postcode1 = []; for (var i = 21000; i < 21999; i++) { postcode1.push({ val: i, text ...

Error: the search variable is not defined

function sorting(type) { $("#parentDiv").empty(); $.getJSON("example_data.json", ({ Find })); function Locate(a, b) { return (a[Find.type] < b[Find.type]) ? -1 : (a[Find.type] > b[Find.type]) ? 1 : 0; }; } The example_data.j ...

Error: Unable to execute decodeHtml because it is not recognized as a function

After transitioning to VueJS 2, I encountered a challenge. While using a filter that calls a custom function, I received the error message: TypeError: this.decodeHtml is not a function Below is my code snippet: new Vue({ el: '#modal' ...

Issue with Laravel 5.7 Autocomplete search: JavaScript unable to recognize the specified route

I've been following a tutorial on this video: https://www.youtube.com/watch?v=D4ny-CboZC0 After completing all the steps, I encountered an error in the console during testing: jquery.min.js:2 POST http://apr2.test/admin/posts/%7B%7B%20('autocom ...

I'm currently working on storing my data in a Node.js REST API, but I keep encountering an issue with the error message "req.status is not a function"

router.post('/savedata',function(req, res){ console.log(req.body); var data={ firstname:req.body.firstname, lastname:req.body.firstname, password:req.body.password, email:req.body.email, created:req ...

Can I legally declare an array with size 0 in C++17?

int main() { int n[0]; } In the case of Clang 4.0, the code provided is considered to be correct. However, according to : It is specified that the size of an array must be greater than zero. So, the question arises: Is it acceptable to declare ...

Executing getJSON requests in perfect synchronization of time

For my weather project, I have two JSON requests to make. The data from the first request is needed in order to personalize the second request for the user. The first request retrieves the latitude and longitude of the user, which are then required for the ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

Struggling to reset the jscrollpane scroller

When using jscrollpane in my horizontal division to enable scrolling, I encounter an issue when loading data with ajax. The scrollbar doesn't appear until the browser width is changed. To address this, I currently utilize the following method to rein ...

Removing the gridlines in a Linechart using Apexcharts

I am experiencing issues with the grid and Nodata options on my Apexchart line chart. noData: { text: none , align: 'center', verticalAlign: 'middle', offsetX: 0, offsetY: 0, style: { color: undefined, fontSize: &apo ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Converting CSDL format into JSON data structure

Is there a way to convert data retrieved in CSDL format from an Oracle DB into JSON format using NODE JS? export async function getRecepFarma(req: Request, res: Response): Promise<Response> { const conn = await connect(); const result = await ...

Dealing with Superagent and Fetch promises - Tips for managing them

Apologies for posing a question that may be simple for more seasoned JS programmers. I've been delving into superagent and fetch to make REST calls, as I successfully implemented odata but now need REST functionality. However, I'm facing confusio ...

Redux action intensifies upon socket events

I have a Reactjs and Redux application that works well with axios. However, I would like to integrate socket.io into it. In my redux action, I tried the following: export const getOne = (id) => async dispatch => { socket.emit('getOne', i ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

Interconnected Dropdown Menus

I've implemented the cascading dropdown jQuery plugin available at https://github.com/dnasir/jquery-cascading-dropdown. In my setup, I have two dropdowns named 'Client' and 'Site'. The goal is to dynamically reduce the list of si ...

What is the best way to swap out elements in my string with those from an array?

Struggling to replace special characters in file names before saving them to the Windows filesystem due to compatibility issues. For my initial approach, I used the replace() method repeatedly on the string to replace specific special characters. Here&apo ...

What methods can be used to protect (encrypt using Java code) the information in a login form before it is sent to a servlet for

One major concern I have involves sending encrypted data (encrypted before sending the request) to a servlet. I attempted to call a function that encrypts passwords as an example, but I encountered difficulty passing values from JavaScript to Java code in ...