9

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.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, but not sure I understand, where does search_text go ? and didn't you mean the forEach loop to be on filtered ?
I was going to answer exactly the same =) Here's a simple fiddle jsfiddle.net/bmleite/syYxa
the fiddle is great ! thx, but it lacks checking which items are actually selected,
Lol... thanks @MarkRajcok... I'm full of typos today apparently.
1

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>

1 Comment

What about the case that after an selection one element will be deselected? How to handle the deselection of the Select All Button?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.