AngularJS Table Checkbox Selection Helper Functions

I am feeling completely lost and could really use some assistance. I have been looking at different examples but nothing seems to be helping me out.

I have created a dynamic table with checkboxes. Whenever a row is selected, its id gets added to an array and displayed at the top of the table.

What I am looking for is the code to implement the select all checkbox functionality. When all rows are selected using the select all checkbox, I want their ids to be displayed.

Below is the code snippet for the table:

<table>
<thead>
  <tr>
    <th>
      <input name="all"
      type="checkbox"
      ng-click="selectAll()" />
    </th>
    <th>ID</th>
    <th>Date</th>
  </tr>
</thead>
<tbody ng-repeat="x in cons">
  <tr>
    <td>
      <input type="checkbox" 
      name="selectedids[]"
      value="{{x.id}}"
      ng-checked="idSelection.indexOf(x.id) > -1" 
      ng-click="toggleSelection(x.id, idSelection)"> </td>
    <td>{{x.id}}</td>
    <td>{{x.title}}</td>
  </tr>
</tbody>

app.js:

  $scope.idSelection = [];
$scope.toggleSelection = function toggleSelection(selectionName, listSelection) {

    var idx = listSelection.indexOf(selectionName);
    // if currently selected
    if (idx > -1) {
        listSelection.splice(idx, 1);
    }
        // if newly selected
    else {
        listSelection.push(selectionName);
    }
};


//$scope.selectAll=function(){}
//Need code for this function to work

Check out this demo: http://plnkr.co/edit/m9eQeXRMwzRdfCUi5YpX?p=preview.

Any guidance on this would be greatly appreciated.

Answer №1

To effectively manage the state of whether 'All' is currently active or not, a variable is required. When 'All' is not active, a new array containing all item IDs is generated using the `map` function and then passed to the `idSelection` function. However, if `allSelected` is active, an empty array is passed to `idSelection`.

$scope.allSelected = false;

$scope.toggleAllSelection = function() {
  $scope.allSelected = !$scope.allSelected;

  if($scope.allSelected) {
    $scope.idSelection = $scope.items.map(function(item) {
      return item.id;
    });
  } else {
    $scope.idSelection = [];
  }
}

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

Getting nested documents from an array in Meteor and MongoDB: A step-by-step guide

This is a continuation of my previous inquiry on this topic here on stackoverflow.com. Firstly, I want to express my gratitude to @David Weldon. With his guidance, I successfully organized my update. However, upon retrieving the data from the database, I ...

Customize input box type based on JSON data using ng-repeat directive in AngularJS

Looking to implement a dynamic form using angular JS. I can successfully use ng-repeat to iterate through JSON fields and display an input box for each. Now I need to customize the input type based on field data from JSON, whether it's 'input&a ...

Retrieve the live value for plugin settings following the completion of DOM loading. (Fineuploader plugin)

I am seeking assistance with a situation. I am utilizing Fineuploader and I need to access and transmit the value of an input field (which will serve as the file group title). To achieve this, I am using the path to a server-side script (as I did not wri ...

The Textfield component in Material UI now automatically sets the default date to the current date when using the "date" type

I am using Material UI's textfield with the type set to "date" and I'm experiencing an issue where the date defaults to the current date instead of mm/dd/yyyy. Is there a way to prevent this behavior and display mm/dd/yyyy when the user loads the ...

Kendo Template Function: Angular JS version 1.6

I'm working with a currency column that looks like this: { field: 'INVOICE_AMOUNT_ORIGINAL', title: $translate.instant('invoiceAmount'), format: '{0:n}', template: '#= currency(dataItem.INVOICE_AMOUNT_ORIGIN ...

The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Updating the time and date format within an AngularJS application

I am receiving date and time data from the API and would like to adjust the format. The current format is "2016-05-12", "07:17:35". Desired format: 12-May-2016 7:30 PM: <table class="table"> <thead> <tr> <th& ...

Mirror the content of my div code onto a two-dimensional plane using an A-frame

Query I am currently developing a 3D scene using A-Frame () and I am in need of a solution to mirror an HTML div onto a plane within the A-Frame environment. For instance, imagine a scenario where there is a div at the bottom left corner of the screen fun ...

What is the best way to test a route using nock and request-promise when the URL includes single quotes?

Trying to test an API call using nock + request-promise is resulting in an error due to mismatched routes caused by single quotes in the API's url. The problem arises from request-promise url encoding the quotes while Nock does not. You can view the ...

Why won't Node.js let me redirect to my error page?

I've been putting together my newsletter project with the Mailchimp API, everything seems to be working fine except for when I try to redirect to a failure page if the status code is not 200. The browser shows an error message saying 'localhost r ...

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...

Angular ng-repeat not recognizing nested ng-if conditions

Hey there, I'm trying to make sure that only the option corresponding to the code used by the client to log in is displayed. The HTML should show the option that matches the client's login code. View: <div class=""> <select id="custo ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

I am experiencing an issue where the data on the server is not being updated when I click the "back" button in the browser using jQuery, Ajax,

Here's the issue at hand: Upon clicking the "purchase" button, it changes color, updates the link, and adds the product to the cart: $(document).ready(function(c) { $('.item_add').click(function (event) { var addButton = $(this).c ...

in AngularJS, check for object attributes existence before proceeding to use them

Currently, I have a filter function that is designed to check the latitude and longitude distance of objects within an array against the range selected by the user. However, there is a problem in which some objects within the array do not possess latitude ...

Using Vue.js within Cordova platform allows developers to create dynamic

Having trouble integrating a Vue.js app into Cordova. Everything seems to be working fine, except I'm unsure how to capture Cordova events (deviceready, pause, etc.) within my Vue application. Using the Webpack template from vue-cli. This is my file ...

Utilizing a try/catch block for validating a JSON file is ineffective

I'm attempting to verify if a received string is JSON and I experimented with the code below: try { JSON.parse(-10); // Also tried with "-10" }catch(e) { console.log('inside catch'); } Surprisingly, the code never enters the catch ...

The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging ou ...

Guide on how to append input field data to a table using jQuery

My current project involves working with a table, and I have encountered some challenges along the way. Typically, I have 4 input fields where I can input data that is then sent to the table in my view. However, if I exceed 4 values and need to add more, I ...