Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs filter and select all checkbox

Tags:

angularjs

I have an array of items I am displaying with

<tr ng-repeat="i in items | filter:search_text" ...>

the items have a check box that denotes "selected" or not. how can I know which items are displayed by the filter when I need to do something like call a delete function that will delete all selected items ?

Items which have been selected (checked in the checkbox) and then hidden by filtering are still selected. I need a way to know which item is on screen at the moment.

like image 899
Unenumrated Avatar asked Feb 26 '13 14:02

Unenumrated


2 Answers

You can use $filter to call a filter in your controller.

app.controller('MyCtrl', function($scope, $filter){ 
   var filter = $filter('filter');

   $scope.items = [/* your items here */]

   $scope.selectAllFilteredItems = function (){
      var filtered = filter($scope.items, $scope.search_text);

      angular.forEach(filtered, function(item) {
         item.selected = true;
      });
   };
});

You would then call selectAllFilteredItems() in an ng-click or anywhere else you needed to.

like image 139
Ben Lesh Avatar answered Nov 02 '22 05:11

Ben Lesh


Not really super polished, but it works.

In your controller

var filter = $filter('filter');
$scope.item_ids = [];
$scope.selectAllFilteredItems = function (){
    var filtered = filter($scope.items, $scope.searchText);
    angular.forEach(filtered, function(item, key) {
        if($scope.item_ids.indexOf(item.id) == -1){
            $scope.item_ids.push(item.id);
            $scope.items[key].selected = true;
        }else{
            $scope.item_ids.splice($scope.item_ids.indexOf(item.id),1);
            $scope.items[key].selected = false;
        }
    });
};

Then in the table you have a checkbox to select all or unselect all.

<table class='table table-striped'>
    <tr>
        <th><input type="checkbox" ng-click="selectAllFilteredItems()"></th>
    </tr>
    <tr ng-repeat="item in items | filter:searchText">
        <td><input type="checkbox" ng-model="item.selected"></td>
    </tr>
</table>
like image 33
Stirling Avatar answered Nov 02 '22 05:11

Stirling