kkh
kkh

Reputation: 4869

Angular Filter with checkboxes

I have a table with a checkbox in each row.

My tr row as below

<tr ng-repeat="row in rows | filter:searchFilter" > 

The checkbox in each row as below

<input type="checkbox"  value="{{row.id}}" ng-checked="selection.indexOf(row.id) > -1" ng-click="toggleSelection(row.id)" class="chosenRouteCheckbox"> 

And I have an input text as below

<input type="text" ng-model="searchFilter"/>

I have an array of row ids to keep tracked to ensure that they are checked if they are in the array, explaining why I use the indexOf(row.id) > -1 in the input checkbox.

However, when I type something in the input text, it shows correctly the filtered results, but when I click on a button that checks all the input checkboxes, it does not check the filtered ones only, it checks ALL the input checkboxes.

My check all html as below

<a class="btn btn-info pull-right" style="cursor:pointer" ng-click="checkAllRows()" ng-show="all_rows_checked == false">Check All Rows</a>
<a class="btn btn-info pull-right" style="cursor:pointer" ng-click="checkAllRows()" ng-show="all_rows_checked == true">Uncheck All Rows</a>

My check all function as below

 $scope.checkAllRows = function () {
     $scope.all_rows_checked = !$scope.all_rows_checked;
     if ($scope.all_rows_checked == true) {
         for (var i = 0; i < $scope.rows.length; i++) {
             $scope.selection.push($scope.rows[i].id);
         }
     } else {
         $scope.selection = [];
     }
 }

Thanks in advance if anyone can help me!

Upvotes: 2

Views: 1582

Answers (2)

manasi sakhare
manasi sakhare

Reputation: 1051

If all you need to do is check all the check boxes, then why not just write the input checkboxes per row as below:

<input type="checkbox"  value="{{row.id}}" ng-checked="all_rows_checked == true" ng-click="toggleSelection(row.id)" class="chosenRouteCheckbox">

And in your checkAllRows function just do this:

$scope.checkAllRows = function(){
    $scope.all_rows_checked = !$scope.all_rows_checked;

}

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You will need to save filtered array in one more variable and use this reduced array in checkAllRows function to determine if current row needs to be checked:

$scope.checkAllRows = function() {
    $scope.all_rows_checked = !$scope.all_rows_checked;
    if ($scope.all_rows_checked) {
        for (var i = 0; i < $scope.rows.length; i++) {
            if ($scope.filtered.indexOf($scope.rows[i]) > -1) {
                $scope.selection.push($scope.rows[i].id);    
            }
        }
    } else {
        $scope.selection = [];
    }
}

HTML:

<tr ng-repeat="row in filtered = (rows | filter:searchFilter)">

Demo: http://plnkr.co/edit/EQKojsUV8yUqKKUaTq1N?p=preview

Upvotes: 3

Related Questions