Guide to select all the checkboxes within rows using AngularJS

New to AngularJs, I am facing a challenge with the code below. The table is populated using Angularjs and includes a selectAll checkbox in the header that should select all checkboxes in the table when checked. However, due to sorting and filtering capabilities, I'm unsure how to implement this functionality. Can you provide guidance on achieving this?

A Plunker link for reference:

Plunker link

<div class="row">
  <div class="col-lg-12">
    <div class="ibox float-e-margins">
      <div class="ibox-title">
        <h5>Hosts {{ currentPage }}</h5>
         <!--<button class="btn btn-sm btn-warning pad-btn" type="submit" ng-click="reset()" style="float:right;">Refresh<i class="fa fa-history"></i></button>-->
      </div>
      <div class="ibox-content">
          <div class="row">
              <div class="col-sm-4 m-b-xs">
                  <div data-toggle="buttons" class="btn-group">
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option1" name="options" ng-model="pageSize" value="10">10</label>
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option2" name="options" ng-model="pageSize" value="25">25</label>
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option3" name="options" ng-model="pageSize" value="50">50</label>
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option4" name="options" ng-model="pageSize" value="100">100</label>
                  </div>
              </div>
... (remaining text omitted for brevity) Thank You! </p>
    </div></questionbody>
<exquestionbody>
<div class="question">
                
<p>I am new to AngularJs. I have the code below where I have a table and rendering the content of the table using Angularjs. I have a selectAll checkbox on the header on checking of which I need all the checkboxes in the table to get selected. Since I can sort, filter the content, I am not understanding how to select all the checkboxes of the table. Can you please let me know how to get this implementation.  </p>

<p>Also added a plunker for this code </p>

<p><a href="http://plnkr.co/edit/EcdrWNEuTw6hMvVirLnE?p=preview" rel="nofollow">Plunker link</a></p>

<pre><code><div class="row">
  <div class="col-lg-12">
    <div class="ibox float-e-margins">
      <div class="ibox-title">
        <h5>Hosts {{ currentPage }}</h5>
         <!--<button class="btn btn-sm btn-warning pad-btn" type="submit" ng-click="reset()" style="float:right;">Refresh<i class="fa fa-history"></i></button>-->
      </div>
      <div class="ibox-content">
          <div class="row">
              <div class="col-sm-4 m-b-xs">
                  <div data-toggle="buttons" class="btn-group">
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option1" name="options" ng-model="pageSize" value="10">10</label>
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option2" name="options" ng-model="pageSize" value="25">25</label>
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option3" name="options" ng-model="pageSize" value="50">50</label>
                      <label class="btn btn-sm btn-white"> <input type="radio" id="option4" name="options" ng-model="pageSize" value="100">100</label>
                  </div>
              </div>
... (remaining text omitted for brevity) Thanks</p>
    </div>
</exquestionbody>
<answer1>
<div class="answer" i="31389284" l="3.0" c="1436796194" m="1436808598" v="1" a="SmVhbiBDZWRyb24=" ai="4778944">
<p>Try this:</p>

<p>On <strong>thead</strong> change your checkbox line for this:</p>

<pre><code><td><input type="checkbox" ng-change="updateHosts()" ng-model="allHosts"/></td>

On tbody change your checkbox line for this:

<td><input type="checkbox" ng-model="host.checked"/></td>

Change your $scope.newHosts for this:

$scope.newHosts=[
    {
      "id": 1,
      "name": "Pradeep",
      "application": "Angularjs",
      "checked": false
    },
    {
      "id": 2,
      "name": "Praveen",
      "application": "NodeJs",
      "checked": false
    },
    {
      "id": 3,
      "name": "Raj",
      "application": "Java",
      "checked": false
    },
    {
      "id": 4,
      "name": "Ram",
      "application": "Dontnet",
      "checked": false
    }
  ];

Finally, add this method:

 $scope.updateHosts = function (){
  $scope.newHosts.forEach(function(host){
    host.checked = $scope.allHosts;
  });
};

Aditional: Get rid of your update method.

Now, when you click on each checkbox, the variable checked will change inside $scope.newHosts.

Edit

If you just want to check the filtered ones, try this:

    <tr dir-paginate="host in filteredHosts = ( newHosts | orderBy:sortType:sortReverse | filter:name | itemsPerPage:pageSize)" 
        pagination-id="host" current-page="currentPage">

Answer №1

Consider the following solution:

Replace your checkbox line in thead with this one:

<td><input type="checkbox" ng-change="updateHosts()" ng-model="allHosts"/></td>

For tbody, update your checkbox line to the following:

<td><input type="checkbox" ng-model="host.checked"/></td>

Update $scope.newHosts like this:

$scope.newHosts=[
    {
      "id": 1,
      "name": "Pradeep",
      "application": "Angularjs",
      "checked": false
    },
    {
      "id": 2,
      "name": "Praveen",
      "application": "NodeJs",
      "checked": false
    },
    {
      "id": 3,
      "name": "Raj",
      "application": "Java",
      "checked": false
    },
    {
      "id": 4,
      "name": "Ram",
      "application": "Dontnet",
      "checked": false
    }
  ];

Lastly, include this method:

 $scope.updateHosts = function (){
  $scope.newHosts.forEach(function(host){
    host.checked = $scope.allHosts;
  });
};

Additionally, remove your update method if necessary.

Now, whenever you click on a checkbox, the checked variable within $scope.newHosts will be updated.

Edit

If you only want to check the filtered items, try the following:

    <tr dir-paginate="host in filteredHosts = ( newHosts | orderBy:sortType:sortReverse | filter:name | itemsPerPage:pageSize)" 
        pagination-id="host" current-page="currentPage">

Answer №2

If you're looking to enhance your data tables, consider implementing the md-data-table module. You can explore a demo of this functionality here.

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

Leveraging an AngularJS service within Angular framework

I am trying to incorporate an AngularJS service into my Angular project. Below is my main.ts file: import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './app/app.module'; import {UpgradeMo ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Using Angular NgUpgrade to inject an AngularJS service into an Angular service results in an error message stating: Unhandled Promise rejection: Cannot read property 'get' of undefined; Zone:

I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

"Troubleshooting Angular 2 Directives That Cause Errors

Hey there, I'm currently working on understanding ANGULAR 2 routing, but I've encountered an error that's causing some trouble. Here's the issue I'm facing: app/app.component.ts(7,12): error TS2345: Argument of type '{ s ...

What is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

Jasmine encountered an error while trying to compare the same string: 'Expected the values to match.'

I'm encountering an error message, despite verifying that the strings are identical: Expected { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'ty ...

The combination of Stripe, Angular, and TypeScript is not compatible

Attempting to utilize Stripe.card.createToken() in order to generate a token for backend usage has proven to be challenging. Integrating this functionality with Angular and TypeScript requires careful coordination. Currently, the angular-stripe and stripe. ...

Angular 2 is throwing an error, stating that Observable is not defined

I'm currently working with Observable and ChangeDetectionStrategy to notify other components about any changes that occur. However, I am encountering an issue where the Observable object addItemStream is coming up as undefined. Can anyone spot what mi ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

It’s not possible for Typescript to reach an exported function in a different module

Having trouble referencing and using exported methods from another module. I keep getting an error that says 'There is no exported member in SecondModule'. module FirstModule{ export class someClass{ constructor(method: SecondModule ...

Utilizando Typescript com Ionic 2 e AngularJS para autenticar através de um método de post na requisição HTTP e

Greetings and good afternoon to everyone. I hope you all are doing well. I am a beginner in AngularJS, currently using Visual Studio, Ionic 2, and TypeScript. I have successfully connected my app to a REST API in .NET and have implemented a token for tes ...

Angular 2 decorators grant access to private class members

Take a look at this piece of code: export class Character { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{character.name}} detai ...

Tips on selecting specific text from a drop-down menu

After struggling to find a solution for retrieving the text of a selected item from a dropdown, I decided to create a common directive. This directive would allow me to easily access the text for all dropdown items when used in my code. Below is the snippe ...