How to toggle the selection of all checkboxes in an AngularJS ng-repeat object array

Check out this Fiddle Example

In my table, each row contains a checkbox and there is also a checkbox to check all rows and send the ID of the selected/all rows as JSON object.

I have an array of objects from the server-side response (with pagination enabled) stored in the itemsList $scope variable.

Here is the code I am using:

View

<table class="table">
        <thead>
            <tr>
                <th><input type="checkbox" ng-model="allItemsSelected ng-change="selectAll()"></th>
                <th>Date</th>
                <th>ID</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in itemsList track by $index" ng-class="{selected: item.isChecked}">
                <td>
                    <input type="checkbox" ng-model="item.isChecked" ng-change="selectItem(item)">
                </td>
                <td>{{item.date | date:'dd-MM-yyyy'}}</td>
                <td>{{item.id}}</td>
            </tr>
        </tbody>
    </table>
    

Controller

$scope.itemsList = [
        {
            id : 1,
            date : '2019-04-04T07:50:56'
        },
        {
            id : 2,
            date : '2019-04-04T07:50:56'
        },
        {
            id : 3,
            date : '2019-04-04T07:50:56'
        }
    ];
    $scope.allItemsSelected = false;
    $scope.selectedItems = [];

    // This function gets executed when an entity in the table is checked
    $scope.selectItem = function (item) {

        // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
        for (var i = 0; i < $scope.itemsList.length; i++) {
            if (!this.isChecked) {
                $scope.allItemsSelected = false;
                $scope.selectedItems.push(item.id);
                return;
            }
        }

        // If all entities are checked, check the "allItemsSelected" checkbox
        $scope.allItemsSelected = true;

    };

    // This function executes when the checkbox in the table header is checked
    $scope.selectAll = function() {

        // Loop through all the entities and set their isChecked property
        for (var i = 0; i < $scope.itemsList.length; i++) {
            $scope.itemsList[i].isChecked = $scope.allItemsSelected;

            $scope.selectedItems.push($scope.itemsList[i].id);
        }

    };
    

Issues I'm facing...

  • If you check the fiddle example, you will see that on the checkAll() function call, the array is updated with all available items. However, clicking again on checkAll() adds another row to the same object array instead of removing it.
  • I also want the ability to add or remove items from the array when clicking on any row's checkbox.
  • If I manually check all checkboxes, the header checkbox should also be checked.

Answer №1

It seems like you are on the right track. Instead of creating an array solely for selected items, consider using the isSelected property of each item. I have provided a working example in this fiddle: http://jsfiddle.net/MSclavi/95zvm8yc/2/.

If you need to send the selected items to the backend, you can filter out the checked items with:

var selectedItems = $scope.itemsList.filter(function (item) {
    return !item.isChecked;
});

I hope this information is useful for you.

Answer №2

For resolving one of the two uncertainties, this snippet can be quite handy:

$scope.toggleSelection = function() {
    if($scope.allItemsSelected){
        for (var i = 0; i < $scope.itemsList.length; i++) {
            $scope.itemsList[i].isSelected = $scope.allItemsSelected;
            $scope.selectedItems.push($scope.itemsList[i].id);
        }
    }else{
        for (var i = 0; i < $scope.itemsList.length; i++) {
            scope.itemsList[i].isSelected = $scope.allItemsSelected;
        }
        $scope.selectedItems = [];
    }
};

I'm currently seeking a method to address the second issue. Instead of using ng-checked, I would recommend avoiding its conjunction with ng-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

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

Attempting to transmit checkbox data in jade

I am currently developing an app with Express, Node.js, and Mongo. I have encountered an issue while passing checkbox values to my database. My goal is to only pass the values of checked checkboxes back to the database. In my index.jade file, I attempted ...

Is there a way to cancel hiding on a q-dialog?

I'm currently working on integrating a confirmation modal within a dialog box that includes form input fields. The purpose is to alert the user when they try to exit without saving their changes. The modal should appear every time the user modifies th ...

Creating an HTML Canvas effect where images are placed onto another image

Looking to create a similar effect as seen on this website () On this site, users can upload their images (4000 * 400) and have the option to add Mickey Mouse ears over their image before saving it. The Mickey Mouse ear is resizable from all four sides f ...

Tips on how to showcase various information in distinct tabs using VueJS

I am currently working on a website project utilizing the VueJS framework and Vuetify template. My goal is to showcase different content under separate tabs, however, I'm encountering an issue where the same content is being displayed in all three tab ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Error message: "NAN encountered while attempting to extract a numerical value from

I've encountered a strange bug in my coding. I'm working on a weather forecasting website that uses geolocation to identify your city and then utilizes the wunderground API to provide the forecast. The issue arises when manually searching for a c ...

Merging two JSON objects in the absence of one

function fetchData(url) { return fetch(url).then(function(response) { return response.json(); }).then(function(jsonData) { return jsonData; }); } try { fetchData(`https://api.hypixel.net/skyblock/auctions?key=${apikey}`).the ...

Get the Google review widget for your web application and easily write reviews using the Google Place API

I developed a platform where my clients can provide feedback and ratings on my services through various social media platforms. Currently, my main focus is on collecting Google reviews using a Google widget/flow. https://i.sstatic.net/RvPst.png The imag ...

What is the method for extracting JavaScript code as data from a script tag?

I have a file external (let's say bar.js) function qux() {} Then in my webpage, I include it using the script tag: <script type="text/javascript" src="bar.js"></script> I am looking for a way to retrieve the JavaScript code from within ...

Exploring Angular 10: Managing Two Promises in ngOnInit

I am currently working on integrating the Strava API into my Angular app. To summarize briefly: When a user clicks on a button to connect to Strava They are redirected to Strava for authentication (using PKCE) Strava then redirects back to my app with a ...

Problems with select box rendering in Internet Explorer with Materialize CSS

When using materializecss select box in Internet Explorer 9 or higher, scrolling with the mouse button is not working. You must click on the scroll bar inside the select box for it to scroll. This issue does not occur in other browsers. I have attached a s ...

The context of the Nuxt.js3 plugin loses its definition

Currently, I am working on a project that involves Nuxt.js3 and supabase integration. In my plugins/supabase.server.js file (I am still unsure whether using server or client is the best approach), I want to call "supabase = createClient(~~)" from index.vu ...

Importing external components from the parent directory in Next.js is a seamless process

I am trying to import react components from an external directory called common into the web-static directory while using nextjs. However, I keep encountering an error that says: Module not found: Can't resolve 'react' in '/Users/jakub ...

Streamlining the login process in AngularJS to eliminate the need for repeated logins

I have set up authentication and authorization using AngularJS, Jersey REST, and Spring Security. Once a user logs in, they can call the "create" method below to save their information: .factory('Session', function () { this.create = functio ...

An issue of an infinite loop arises when utilizing the updated() lifecycle hook in VueJS

I am working on a VueJS application where I need to fetch a list of articles in one of my components. The logic is such that if the user is logged in, a specific request is made, and if not, another request is executed. Below is the snippet of code: <s ...

Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...