ngTable select all data that has been filtered

I have encountered an issue with selecting only the rows from an ng-table that have been filtered. The current code filters the table rows successfully, but it also selects rows that are not displayed:

Controller:

let sampleData = [{id: 1, name: 'John Doe', gender: 'Male'},
    {id: 2, name: 'Jane Doe', gender: 'Female'},
    {id: 3, name: 'Mary Jane', gender: 'Female'},
    {id: 4, name: 'Mary Poppins', gender: 'Female'}];

$scope.tableParams = new NgTableParams({

}, {
    dataset: sampleData
});

$scope.checkboxes = {
    checked: false,
    items: {}
};

$scope.$watch(() => {
    return $scope.checkboxes.checked;
}, (value) => {
    sampleData.map((item) => {
        $scope.checkboxes.items.id = value;
    });
});

$scope.$watch(() => {
    return $scope.checkboxes.items;
}, () => {
    let checked = 0;
    let unchecked = 0;
    let total = sampleData.length;

    sampleData.map((item) => {
        if ($scope.checkboxes.items.id) {
            checked++;
        } else {
            unchecked++;
        }
    });

    if (unchecked === 0 || checked === 0) {
        $scope.checkboxes.checked = checked === total;
    }

    angular.element($element[0].getElementsByClassName('select-all')).prop('indeterminate', (checked != 0 && unchecked != 0));
});

HTML:

<script type="text/ng-template" id="checkbox.html">
    <input type="checkbox" ng-model="checkboxes.checked" class="select-all" value="">
</script>
<table class="table" ng-table="tableParams" show-filter="true">
    <tr ng-repeat="item in $data track by $index">
        <td header="'checkbox.html'">
            <input type="checkbox" ng-model="checkboxes.items[item.id]">
        </td>
        <td data-title="'Name'" filter="{'name': 'text'}">
            {{item.name}}
        </td>
        <td data-title="'Gender'" filter="{'gender': 'text'}">
            {{item.gender}}
        </td>
    </tr>
</table>

After filtering the table by name or gender, selected rows display correctly. However, issues arise when clearing the filter as previously filtered out rows remain selected. The same problem occurs when selecting all filtered rows and then performing an action that is supposed to target those selections (all ids get selected for the action).

I am looking for a solution to only select the rows that are currently filtered. Any guidance would be appreciated. Thank you.

Answer №1

Successfully managed to make it work by introducing a new tableData object within the $scope. This enables me to store the filtered data for checking selected items.

let sampleData = [{id: 1, name: 'John Doe', gender: 'Male'},
    {id: 2, name: 'Jane Doe', gender: 'Female'},
    {id: 3, name: 'Mary Jane', gender: 'Female'},
    {id: 4, name: 'Mary Poppins', gender: 'Female'}];

$scope.tableData = {
    filteredData: [],
    checkboxes: {
        checked: false,
        items: {}
    }
};

$scope.tableParams = new NgTableParams({
    page: 1,
    count: 10
}, {
    total: data.length;
    getData: ($defer, params) => {
        let filter = params.filter();
        let count = params.count();
        let page = params.page();
        let filteredData = filter ? $filter('filter')(data, filter) : data;

        params.total(filteredData.length);
        $scope.tableData.filteredData = filteredData;

        $defer.resolve(filteredData.slice((page - 1) * count, page * count));
    }
});

$scope.$watch(() => {
    return $scope.tableData.checkboxes.checked;
}, (value) => {
    $scope.tableData.filteredData.map((item) => {
        $scope.tableData.checkboxes.items[item].id = value;
    });
});

$scope.$watch(() => {
    return $scope.tableData.checkboxes.items;
}, () => {
    let checked = 0;
    let unchecked = 0;
    let data = $scope.tableData.filteredData;
    let total = data.length;
    let checkboxes = $scope.tableData.checkboxes;

    data.map((item) => {
        if (checkboxes.items[item].id) {
            checked++;
        } else {
            unchecked++;
        }
    });

    if (unchecked === 0 || checked === 0) {
        checkboxes.checked = checked === total;
    }

    angular.element($element[0].getElementsByClassName('select-all')).prop('indeterminate', (checked != 0 && unchecked != 0));
});

I am uncertain if this is the most efficient approach. Also, there seems to be an issue where the select all checkbox state does not become indeterminate after filtering, selecting all, and then clearing the filter.

Answer №2

Try switching to this code in your second watch: $scope.tableData.filteredData; it could resolve the issue you are facing

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

Is it possible to use contenteditable along with ng-model within an ng-repeat loop?

My current dilemma involves using the ng-repeat directive to generate a list of span elements. Each span includes both the contenteditable attribute and the ng-model directive for two-way data binding. Initially, everything functions as expected until I a ...

Filtering Wordpress content on the fly with a dropdown menu (utilizing php and ajax)

Objective: My goal is to create a dynamic webpage that allows visitors to choose a specific month and year from a dropdown menu. The content (posts) on the page should automatically change based on the selected values. Currently, I am using the following ...

Enclose Angular $resource requests that do not return POST data

Currently, I am working on enhancing my $resource requests by implementing a straightforward wrapper. The primary objective is to incorporate some logic before the request is actually sent. For guidance, I referred to an informative article authored by Nil ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Adjusting the size of an element in Angular JS as a textarea expands

I have created a directive that allows for writing and previewing comments, similar to the conversations in Github. The directive consists of two HTML elements: a textarea and a div (utilizing angular-marked). My goal is to dynamically resize the div as I ...

Having trouble with AngularJs and moment.js integration?

Looking to create a simple webpage using Angular Js for date calculations. Utilizing moment.js from http://momentjs.com/ Below is the current code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ...

Utilizing form inputs for uploading images in Ionic framework

I have a platform wherein users can fill out a form and upload a single image before finalizing their submission. Now, I am attempting to replicate the same functionality using the Ionic framework. Here's my progress thus far: 1. Installed ngCordov ...

the ng-click event handler is not triggering the function

<body ng-app="groupChatApp" ng-controller="groupChatController"> <div id="error-container">{{errorValue}}</div> <div ng-model="changeForm" id="changeForm"> <input id="name" type="text" name="name" value="" placeho ...

Optimizing rest service calls with $resource

I am currently learning about the $resource to utilize RESTful Web Services. For my first attempt, I created a factory like this : 'use strict'; angular.module('BalrogApp').factory('Req', ['$resource', function($r ...

Obtain the date format of the current locale script in use

When I need to i18n my application, I dynamically import the locale script: $scope.setCountry = function(countryKey) { // Importing Angular locale dynamically based on country select var imported = document.createElement('script' ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

AngularJS powered edit button for Laravel route parameter

I have a data list that needs to be edited using an edit button. When clicking the edit button, I need to send the ID to a Laravel controller in order to fetch the corresponding data. The initial listing was created using Angular JS. <a class="btn" hr ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

Optimal Procedure for New Users Form (Jade / Angular) in HTML

I'm currently working on integrating a form into my app for users to create tasks. This form should only appear the first time a user attempts to create a task. As someone who is not very experienced with frontend development, I find myself wondering ...

Enhance user interface by dynamically updating date options

Incorporating AngularJS ui-date to link Jquery datepicker, I currently have two date pickers on my page - one labeled 'start' and the other 'end.' I am seeking a way to modify the initial value of the end date based on the start date. ...

Struggling to incorporate my provider into the configuration

Inside app/providers/weather.js: angular.module('forecast').provider('Weather', function() { var apiKey; this.setApiKey = function(key) { if(key) apiKey = key; }; this.$get = function() { return { ... // Som ...

Executing multiple AJAX requests with promises in Angular based on an array of values

I have been working on implementing multiple ajax calls in sequence using Angular. Interestingly, everything seems to be working fine when I use $.ajax, but when I switch to using $http for server requests in Angular, things start to go awry. Both methods ...

Transferring $scope information to resolve in $stateProvider.state

In the app.teams.show parent state, "team" is stored in $scope.data.team. From within a controller, I can access $scope.data.team and thus $scope.data.team.organization_id. The question is: How can I retrieve $scope.data.team.organization_id from inside t ...