AngularJS offers a variety of 'select all' checkboxes tailored for specific lists of checkboxes

Within my webpage, I have three different sets of checkboxes. Each set includes a "select all" checkbox. Instead of repeating code lines, I am implementing a single function with a parameter to select specific checkboxes within each set.

      $scope.selectAll = function(array) {
            angular.forEach(array, function(item) {
                 item.Selected = $scope.model.selectedAll;
             });
       };

Here is the HTML:

   <input type="checkbox"
            ng-model="model.selectedAll" 
            ng-change="selectAll(categories)" >

This approach allows me to easily select all checkboxes in a specific array. However, there is an issue - $scope.model.selectedAll affects all lists, causing the "select all" checkbox to be checked in every list when selected in one.

While I understand the problem, I am unsure how to address it. I have considered creating separate variables for each list, but since the function uses a parameter and the array is unknown, associating a variable with it would not work.

Is there a solution to this problem that does not involve duplicating code for individual sets of checkboxes?

Thank you in advance.

here is my plunker

Answer №1

Your approach in linking various entities to the same model tightly isn't ideal as it hinders their separation. To achieve better separation, consider using distinct models for each entity. Here are a few strategies you can implement:

Employing Unique Models

One method is to enhance your code's generality by creating individual models for every checkbox, like this:

html

<input type="checkbox"
       ng-model="model1.selectedAll" 
       ng-change="selectAll(categories1, model1.selectedAll">

JS

$scope.selectAll = function(array, value) {
  angular.forEach(array, function(item) {
    item.Selected = value;
  });
};

Utilizing a Base Model

Alternatively, if managing numerous variables seems cumbersome, group them under a single base model - especially useful for dynamically generated elements.

html

<input type="checkbox"
       ng-model="modelSet[key].selectedAll" 
       ng-change="selectAll(categories, key)">

JS

$scope.selectAll = function(array, key) {
  angular.forEach(array, function(item) {
    item.Selected = $scope.modelSet[key].selectedAll;
  });
};

Remember, ensure that your selection function retrieves necessary information from the view rather than relying solely on $scope. Providing context to utility functions enhances reusability and reliability.

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

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

Having trouble retrieving exchange rates from the state in React after making an API call

import React, { Component } from 'react'; import axios from 'axios'; class SearchCurrency extends Component { constructor() { super(); this.state = { data: {} } } componentDidMount() { axios .get(&apo ...

Resolving CORS problem: Eliminating the 'Access-Control-Allow-Origin' Response Header in Angular

Recently, the backend API located at has been proxied by an F5 device which automatically includes the CORS header Access-Control-Allow-Origin: * in all responses. However, the GUI code seems to also be adding a CORS header with Access-Control-Allow-Origi ...

Initiate an animation in Wordpress once the entire page has finished loading

Recently, I incorporated some "raw html" elements with animations into my WordPress site. However, the issue I'm facing is that these animations kick off as soon as the page loads, without waiting for the preloader to complete and display the actual c ...

In a scenario where multiple fields need to be incremented, one can accomplish this by incrementing one field every time while also increasing the other field only if it exceeds a

When trying to decrement class_number, everything works fine. However, the issue lies with number_of_classes not being decremented due to the usage of the $gt operator. posts.update({ 'title':doc.title, 'author':doc.author, 'class ...

What is the best way to merge two AngularJS form validation directives criteria using CSS?

When both $dirty and $invalid are true, I would like the input fields to have a red background. However, I am only able to do this one by one, which is not ideal. input.ng-dirty && input.ng-invalid { background-color: red; } ...

Retrieve a JSP list item using JavaScript

In my setup, I have a Servlet, JSP page, and JavaScript. I pass a list from the servlet to the JSP, where it displays the results. Each result is shown in a table and includes a delete button. My goal is to retrieve the ID of the result I want to delete an ...

Using jQuery to detect changes made with jQuery while updating

Despite the seeming paradox, I am currently exploring how to detect a change on a text input when its value is updated via jQuery. While the user interacts with the page, my JavaScript function performs this action: $('#LicenseOwnerId').val(com ...

Having trouble with React and Webpack's Extract Text Plugin. I can't seem to get my styles to work from bundle.css, even though they are functioning fine from bundle.js. Any advice on

Currently, I am working on my SCSS styles and using CSS modules to keep each component's styles separate. However, I have encountered an issue with generating a separate CSS bundle for the production build. While I am able to generate a separate CSS ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

What steps do I need to follow in order to set up webpack.config.js to convert my HTML file to JS in a Reactjs application

My current folder structure is shown below: https://i.sstatic.net/mSdcH.png Upon attempting to run my React app, I encountered the following error: Failed to compile. ./src/css/owl.html 1:0 Module parse failed: Unexpected token (1:0) To resolve this is ...

Exploring the integration of JSONP with the unmatched features of Google

I am attempting to utilize the Google maps directions API by using jquery $.ajax. After checking my developer tools, it seems that the XHR request has been completed. However, I believe there may be an issue with the way jquery Ajax handles JSON.parse. Y ...

What could be the reason for the malfunction of this angular binding?

Looking at the HTML below: <input type="checkbox" name="person" [(ngModel)]="person.selected" /> This input is part of a ngFor loop. Testing has revealed that despite some values of selected being true and others false, all checkboxes appear check ...

Using Regular Expressions in an ExpressJS Router

When working with ExpressJS, is there a way to combine the following routes into one using RegEx? app.get(/^\/blog(?:\/p(\/\d+)?)?$/, blog.list); ...

The jwplayer getDuration function functions correctly in the Chrome console, but it encounters issues when used in C# alongside IJavaScript

I am encountering an issue with the getDuration command in jwplayers. I suspect that it might be related to a translation problem between C#'s javascript executor. Any help or insights are greatly appreciated. Here is the problematic C# code: IJavaS ...

What is the technique for choosing the parent's ID with jQuery?

When a user clicks on any team, I need to retrieve the parent's parent ID. For example, if someone clicks on a Premier League Team, I want to store the ID 2 in a variable called league_id. Here are my attempts so far: Using Closest Method $('u ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

Is it necessary to have two servers in order to operate an ext JS application using Node.js on the server side?

I recently began working with Node.js and have started using a sample application where the server-side was written in Node. I am currently developing and running my Ext JS application using Sencha Cmd on localhost:1841. At the same time, I have a server.j ...